CS62 - Spring 2021 - Class 2

Example code in this lecture

   ClassBasics

Lecture notes

  • Administrative
       - how did lab go?
       - class notes online
       - video recordings
          - I'll try hard to keep them mostly myself, though occasionally I may end up capturing you all in the videos. I'm not sharing the link publicly, but please let me know if this makes you uncomfortable
          - please do attend class however you feel most comfortable. In particular, I don't expect you to have your video camera on if you're not comfortable
       - mentor hours and office hours
          - hours and zoom links on sakai
          - starting today (with a few adjustments this first cycle)

  • Recall the BasicCard class from the ClassBasics code
       - can we create cards that are not valid for a normal deck of cards?
          - Yes!

          BasicCard card = new BasicCard(10000, "banana");

       - how do we prevent this?

  • Look at the BetterCard class from the ClassBasics code
       - We've added two methods: isValidNumber and isValidSuit
       - Anything new?

  • if/else statement
       - Java supports:
          - stand-alone if statements
          - if/else statements
          - "if/else if" statements
       - like other constructs, the condition needs to be in parentheses and the code inside the block surrounded by {}
       - else statement is optional
       - the "else-if" statement is just an else followed by another if

  • boolean operations
       - what boolean operations have you seen?
       - In Java:
          - and is &&
          - or is ||
          - not is !

  • == vs. equals
       - when you declare a variable in Java it makes space for it in memory
       - if the variable is a primitive type (one of the 8 lowercase ones, called primitives: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) then the value that the variable is holding is the actual value (e.g. the number)
       - if the variable is not a primitive type (e.g. String, BasicCard, etc.), then the variable holds a *reference* to the object
          - for example, we can print out the BetterCard variable to see what is stored in it:
             - you see the type
             - followed by an @
             - followed by a number. This number is the actually a memory location (sort of)
       - when you ask if two variables are ==, you're asking if the two values where the variables are stored are the same
          - for primitive types, this will do the intuitive thing
          - for non-primitive types, they will only be equal if they reference the same object!

             BetterCard card = new BetterCard(10, "heart")
             BetterCard card2 = card;

             System.out.println(card == card2);

             - this will give us true

             BetterCard card = new BetterCard(10, "heart")
             BetterCard card2 = new BetterCard(10, "heart")

             System.out.println(card == card2);

             - this will give us false!
       - If you want to ask if two object are equal (that is equivalent), then you you need to call the equals method
          - note that this is a method that YOU must implement if you're creating a new class
             - more on this in a minute!

  • information hiding
       - in addition to accessing methods with the . (dot) notation, you can also access some variables associated with a class
          - accessing instance variables directly is bad coding practice, so don't do it!
          - unfortunately, other people besides ourselves might use our code and so we want to make sure that we protect our data
          - for example, look at the following code:

             BetterCard card = new BetterCard(10, "hearts");
             card.suit = "banana";
          
             System.out.println("Card number: " + card.getNumber());
             System.out.println("Card suit: " + card.getSuit());

             - We went through all that work trying to protect the integrity of our data through the constructor and someone can still mess it up!

  • public and private
       - one of the powers of Java is that you only expose the methods that the user needs to your class and can hide everything else
       - Java allows you to control what information code outside of your class has access
       - to do this we can declare methods and variables to be either public or private by listing this at the beginning of their declaration
          - public means they are accessible to anyone
          - private means they are only accessible inside the class
       - some rules of thumb
          - all instance variables should be private
             - if you need to give someone access to read the variable or set the variable, do it through public methods!
          - the constructor(s) is almost always public
          - methods that define the external functionality of the class/object should be made public
          - all other methods should be made private
       - what should we make public and what should we make private?

  • look at ProperBetterCard class in ClassBasics code

  • how do we check if two cards are equal?
       - check to see that their the same suit and same number
       - public or private?
          - public!

  • look at the Card class in ClassBasics code
       - what is new/added?

  • equals
       - I've added an equals method to check if two cards are equal
       - what does other.number == number check?
          - checks to make sure that *this* object's number is the same as the one that's been passed in
          - note we could also have written this as other.getNumber() == number
             - either way is fine for this class
             - since we're inside the class, we can access any private instance variables

  • toString
       - It's kind of annoying always having to call the getNumber and getSuit method when we want to print out a card
       - If we try and print out a card right now, though, it prints out the memory location
       - We can override this behavior by defining a toString method, specifically:
          public String toString()

          - the method is called on the object and returns a String representation of that context
       - Anytime an object is used in a String context (e.g. for printing), then this method is called
       - Look at the toString method in the Card class
          - returns a new String that is the number plus the suit
       - Now, if we try and print out a card:
          Card c = new Card(10, "hearts");
          System.out.println(c)

          Java calls the toString method and we get a much better printout!
       - In fact, any time it's used in a string context, e.g.
          Card c = new Card(10, "hearts");
          String s = "The card is: " + c;
          System.out.println(s);

          the toString method is called!

  • constants
       - at the top of the class I've defined two other instance variables, MIN_NUMBER and MAX_NUMBER. These are "constants".
          - I've used them below in the isValidNumber method
       - constants are variables that represent values that do not change in the code based on how the code is run
       - We can access them just like any other instance variable
       - Why use constants?
          - can make the code easier to read
          - makes the code easier to update maintain
             - if I want to change the value, I can just change it at the top
             - this is particularly critical if we're using the same constant in many places   
       - to indicate that they're constants, I make them all caps
          - this indicates to anyone reading the code that they're constants
       - to indicate to Java that they're constants (and therefore yell at me if I try and change them) I add the keyword "final"
          - if I try and change a variable that has been set as final, Java will yell at me

          MIN_NUMBER = 12; // Not valid

  • static
       - variables
          - Everything in Java has to be inside a class
          - For instance variables, that means that each time we get a new copy of the object, we get extra copies of the variables
          - For constants, that means each copy of the object will have it's own versions of the constants. Does that make sense?
          - No!
             - if we declare a variable to be static, there's only one version of it PER class, NOT per object
          - all constants we will declare as static

       - methods
          - Java does not have functions, it only has methods
             - a function is a standalone piece of code that is not associated with a class
             - a method is called on an object, e.g. variable.methodName(...)
          - There are some times when we might want to have function-like behavior? Any ideas when?
             - Some things really should just be function (e.g., math operations like round, abs, etc. -- https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html)
             - our code has to start somewhere. Chicken and the egg problem: what code constructs the first object?
          - For these reasons, there are static methods
          - details:
             - static methods can be called *without* instantiated an object
                - if you're inside the class, you can just write the name of the method (though this isn't that different from calling a non-static method)
                - if you're outside of the class, you can call it by saying the class name . (dot) the method name

                   MyClass.staticMethodName(...)
             - static methods cannot access any non-static instance variables (instance variables are associated with an instance of the class).

  • We're now able to understand the main method!!!
       - public: accessible outside of the class
       - static: stand-alone method that does not access/require any state of an object (i.e. access instance variables)
       - void: doesn't return anything
       - main: name of the method
       - String[]: an array of Strings
       - args: the name of the parameter


  • JavaDoc: documentation in Java
       - JavaDoc is a way of commenting your code that *also* allows for html documentation to be generated!
       - http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html
       - a way for you to communicate the "interface" to other programmers/users
       - /** is the beginning comment delimiter for classes/methods
          - if you type this above the class or a method and hit return, Eclipse will automatically generate a template for you!
       - Two basic parts
          - The document comment, which is written in HTML and is the first non-whitespace-line chunk of text
       - block tags. The main ones we'll use are below, but many more online
          - @author
          - @param
          - @return
          - @throws
       - We can generate the HTML from the comments using eclipse (or on the command line)
          - In Eclipse: Project->Generate Javadoc...
          - in the left window, select the classes that you want to generate the javadoc for (generally, you should do one project at a time)
          - select the destination (the "doc" folder within the project is a good place)
          - click "finish" (or "next" if you'd like other options)
          - generate HTML output with the documentation!