CS62 - Fall 2026 - Class 2
Example code in this lecture
ClassBasics
Lecture notes
Administrative
- how did lab go?
- class notes online
- mentor hours and office hours
- mentor hours posted (starting today!)
- office hours starting next week
- Assignment 1 posted soon!
- AI and copilot
designing a class in Java
- three key things when designing a class:
- what are the methods we want the object to have?
- what types of things do we want the object to do?
- what types of questions might we want to ask about the object?
- what data do we need to keep track of *per* object?
- what differentiates one object of the class from another?
- what information do we need to make or create a new object of that class?
let's design a card class to represent a playing card
- what methods do we want the object to have?
- what suit?
- what number?
- maybe:
- face-up/face-down?
- change suit/number?
- location?
- what data do we need to keep track of per card?
- number
- suit
- maybe: location, face-up/face-down
- what information do we need to know to create a new card?
- number
- suit
writing a class in Java
- first, we tell Java that we're declaring a new class
public class ClassName{
}
- this goes in a file that has the same name as the class with the extension .java
- by convention, class names are capitalized
- for all of the data that we want to store, we create "instance variables"
- these are just variables declared inside of the class
- they are available to methods declared inside the class
- for each bit of functionality we want, we write methods
- the "constructor" of a class is a method that has the same name as the class and NO return type
- it's used to create (or construct) a new object
look at the BasicCard class in the
ClassBasics code
- two instance variables: number and suit
- each card object will have its own copy of these variables
- 4 methods (including the constructor)
- all are very simple!
- BasicCard is the constructor and is called when we're creating a new card
- it takes two parameters
- all it does is store these two parameters away
- getSuit and getNumber
- just give data back
- cheat()
- doesn't take any parameters or give anything back
- alters the state of the card
creating a new object
- now that we have defined our class, we can create a new object that is an instance of that class
- creating a new class also creates a new type
BasicCard card = new BasicCard(10, "hearts")
- BasicCard is the type
- card is the name of the variable
- this first part is just like what we've been doing all along
- = (assignment)
- new: keyword that tells Java to create a new object
- BasicCard(...) is the call to the constructor
- Java creates a new object
- that object has its own copies of the instance variables
- the constructor code is then called
main
- ALL Java programs have to start in a "main" method
- the syntax for the main method is:
public static void main(String[] args){
...
}
- To run a program, you click on the green arrow button
- VSCode will look for a main method in the currently open class
- and the program will start executing there
look at the main method in the BasicCard class in the
ClassBasics code
- constructs two different card objects
- prints out the number and suit for the two cards
- calls the cheat method on card1
- then prints out the number and suit for the two cards again
- when you run the code:
- you see each of the cards gets their own copies of the instance variables
- each object has it's own state
- the cheat method changes the state of card1, but card2 is unaffected
Arrays in java
- In the example above, we created two cards
- What if we wanted to create 10 cards? 20?
- We'd have to have variables for each one!
- Arrays (kind of like lists) allow us to store multiple objects in a single variable
- creating lists
BasicCard[] cards = new BasicCard[10];
- The type of the contents variable is an *array* of BasicCards
- it holds exactly 10 cards
- by default, the values in the array will be empty, so be careful
- length: you can tell the number of elements in it using .length
cards.length
- would give us 10
- indexing: like in python, we use square brackets to get at items in the array
cards[0] // first item
cards[3] // fourth item
- arrays are NOT lists
- lists start out empty and we can fill them up, e.g., via append (or add)
- arrays are always the same size!
- the values start out as empty (more on this later)
- often we'll have a for loop to initialize the cards
for( int i = 0; i < cards.length; i++ ){
cards[i] = new BasicCard(i+1, "hearts");
}
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!