Professional Documents
Culture Documents
CS/ENGRD 2110
SPRING 2019
Lecture 4: The class hierarchy; static components
http://cs.cornell.edu/courses/cs2110
Announcements
2
Work on A1:
Start early and avoid frustration!
make a group)
Note: 2110 doesn't officially use iClickers, but if you have
one use it! (We'll show the results of the poll, but we won't
record your answers or ever connect your iClicker to your
NetID.)class Time {
public
private int hr; //hour of day, 0..23
private int min; // minute of hour, 0..59
/** Constructor: an instance with h hours and m minutes
Precondition: h in 0..23, m in 0..59 .*/
public Time(int h, int m) {
hr= h;
What happens when this is executed?
min= m;
} t1 = new Time(9, 66);
A. Java throws an error b/c the precondition is violated
B. min will be set to 66 C. min will be set to 59
Big ideas so far
4
Class Object
Extends, is-a
Method toString(), object names, overriding
Keyword this, shadowing
Static components
Running example: Class W (for Worker)
6
/** Constructor: worker with last name n, SSN s, boss b (null if none).
Prec: n not null, s in 0..999999999 with no leading zeros.*/
public W(String n, int s, W b)
/** = worker's last name */
public String getLname()
W@af
lname “Pollack” W
/** = last 4 SSN digits */
public String getSsn() ssn 123456789
boss null
/** = worker's boss (null if none) */
public W getBoss() W(…) getLname()
/** Set boss to b */
getSsn() getBoss() setBoss(W)
public void setBoss(W b) toString()
equals(Object) hashCode()
Contains other methods!
Class Object
7
https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/javax/swing/JFrame.html
What’s in a name?
12
Variable e, declared as
PhD@aa11bb24
PhD e; PhD
contains not the object but the
name of the object (i.e., it is a name “Gries”
reference to the object).
e PhD@aa11bb24 ad1 null ad2 null
PhD advisees 17
Method toString()
13
java.lang.Math
http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
public class W {
private static int numObs; // number of W objects created
/** Constructor: */
public W(…) {
…
numObs= numObs + 1;
} W@bd W@12
} W W
To have numObs contain the lname “Ra” lname “Kn”
number of objects of class W
that have been created, simply numObs 2
increment it in constructors.
Box for W
Class java.awt.Color uses static fields
22
1. B
2. A