Академический Документы
Профессиональный Документы
Культура Документы
Fall 2016
Announcements
• Assignment 13 due Thursday 12/1 at 11:59 pm
• Detailed specifications – follow them
• Last assignment that you can use free late days
• Assignment 14 will be due Thursday 12/8 (last day
of class) – no late days.
• Final is Wed, December 14, 9am – 12pm
• Questions???
Copyright © 2010
Quiz
What is the output ?
class Demo { class Main {
int i; public static void main(String args[]) { Compiler error (d has not been initialized)
} Demo d;
System.out.println(d.i);
}
hello world
Copyright © 2010
Watch class
The instruction System.nanoTime() returns a long integer which is the value of
the internal clock in nano (10-9) seconds since a certain date.
Copyright © 2010
Static Fields
• Suppose you have a class Employee.
• How can you enforce that each employee has a unique ID.
Copyright © 2010
Static Fields
Static fields and/or methods are not copied into each object
Copyright © 2010
Accessing Static Fields
• From inside the class where the field was
declared:
fieldName // get the value
fieldName = value; // set the value
Copyright © 2010
Sections 8.4 & 8.5
• Sections 8.4 & 8.5 of the class text have a couple
more examples of developing Classes
o We do not have time to cover these in detail in class
o You are expected to read them on your own
o Pay particular attention to the TimeSpan class
Copyright © 2010
Introduction to Inheritance
• Inheritance allows us to define a general class and then
define more specialized classes simply by adding new
details to the more general class definition
• A more specialized class inherits the properties of the
general class, so that only the new features need to be
programmed.
Animals
Vertebrates
Mammals
Primates
Homo
Sapiens
Copyright © 2010
Derived Classes
• Consider a college record-keeping system with records about students, faculty, and staff
• Each of these is a "person"
• Each person has a name, date of birth, gender, home address, government ID number
(SSN, etc.)
o We can define a general class to capture this information
o For simplicity, we will just keep track of a name
public class Person { public String getName() {
private String name; return name;
}
public Person() {
name = "No name yet."; public String toString() {
} return "Name: " + name;
}
public Person(String initialName) {
name = initialName; public boolean equals(Object other) {
} if (other instanceof Person) {
Person p = (Person) other;
return (this.name.equalsIgnoreCase(p.name));
public void setName(String newName) {
} else {
name = newName;
return false;
}
}
}
Copyright © 2010
Derived Classes
• All students, faculty, and staff have:
o names,
These fields may need to be initialized,
o date of birth, changed, retrieved, or printed.
Person class.
o SSN, etc.
• Similarly, all faculty & staff have:
o a date of hire, Employee class.
o W-4 tax information,
o a department & manager, etc.
Copyright © 2010
Derived Classes
Class Person is called the base
Class Student is a derived class class (also known as the
(also known as a subclass or superclass or parent class)
child class) of class Person
Copyright © 2010
Is-a Relationships, Hierarchies
• Triangle
• Consider the following geometrical figures. • Line
• Can you built an inheritance hierarchy ? • Pentagon
• Inheritance hierarchy: A set of classes connected by is-a • Ellipse
relationships that can share common code • Rectangle
• Polygon
• is-a relationship: A hierarchical connection where one • Circle
category can be treated as a specialized version of another • Closed Figures
o Every Faculty is an employee • Open Figures
o Every Graduate Student is a Student
Figure
Closed Open
Figure Figure
Copyright © 2010
Inheritance
• Inheritance: A way to form new classes based on existing
classes, taking on their attributes/behavior
o A way to group related classes
o A way to share code between two or more classes
class Employee {
// instance fields
Superclass public String getName() {…}
Base class public double getSalary() {…}
Parent class public Date getHireDay() {…}
public void raiseSalary(double percentRaise) {…}
}
// inherit from Employee class
Subclass class Manager extends Employee {
Derived class private double bonusToShare; }
Child class public setBonus (double bonus) {
this.bonusToShare = bonus; }
Subclass
Extends introduces new
indicate fields and methods
inheritance
Copyright © 2010
Method Overriding
• Sometimes we need to adapt some superclass methods to
specialized needs of the subclass.
• Appropriate superclass methods are redefined = method overriding .
class Employee {
// instance fields
public String getName() {…}
public double getSalary() {…}
public Date getHireDay() {…}
setSigningBonus public void raiseSalary(double percentRaise) {…}
is overridden in public double setSigningBonus () {…}
subclass }
// inherit from Employee class
class Executive extends Employee {
public double setSigningBonus () {
double bonus = super.setSigningBonus;
return bonus + something_else;
}
Call of
setSigningBonus
from superclass
Copyright © 2010
Method Overriding – Example
What is the output ?
Copyright © 2010
Constructors in Derived Classes
• A base class has its own constructors.
o Their purpose typically is to initialize the instance variables declared in the base class
• A derived class has its own constructors
o Their purpose typically is to call a constructor of the base class, and then to initialize
the instance variables declared in the derived class
public class Person { To call a constructor of the
private String name;
base class:
public Person() { super(values);
name = "No name yet.";
}
public Person(String initialName) {
name = initialName;
}
Person(initialName);
…
class Student extends Person {
private int stdNb;
public Student() {
}
Copyright © 2010
Using super
• The call to the constructor of the base class (using super) must be the first
action taken in the constructor of a derived class
• When no call to a constructor of the base class is included, Java automatically
includes a call to the default constructor of the base class
o The default constructor is the one that does not take any arguments
o If the base class does not have a default constructor, you must use super to
call one of the alternate constructors
public class Person { public class Test {
String name; public static main (String[] args){
}
}
Copyright © 2010
The this Method
• Within the definition of one constructor, it can be
appropriate to call another constructor in the same class
• The keyword this is used to call another constructor in the
same class (we saw this several lectures ago)
• Example, add another constructor:
public Student(String initialName) {
this(initialName, 0) // call other ctor
}
Copyright © 2010
The this Method
Compiler error Compiler error
this() should be the 1st statement super() should be the 1st statement
Compiler error
Can’t have both this() and super() The trick !
Copyright © 2010
Calling Overridden Methods
Subclasses can call overridden methods with super
super.MethodName(Parameters);
Example:
public class Undergraduate extends Student {
public double getTuition() {
double baseTuition = super.getTuition();
return baseTuition * .90; //10% discount for undergrads…!!!
}
...
}
Copyright © 2010
Calling Overridden Methods
• Exercise: write the toString method for the Student and
Undergraduate class using super.
class Person{
private String name;
…… public String toString() {
public String toString(){
return super.toString() +
return “Name: “ + name;
}
"\nStudent number: " + stdNb;
…… }
class Student extends Person{
private int stdNb;
……
public String toString(){
return ?????
}
…… public String toString() {
class Undergraduate extends Student{ return super.toString() +
private int level; "\nLevel: " + level;
…… }
public String toString(){
return ?????
}
……
Copyright © 2010
Person
- name : String
+ Person() How come we had to use super to call
+ setName(String) : void the toString() method of the parent class?
+ getName() : String
+ toString() : String
+ equals(Object) : boolean
extends public String toString() {
return super.toString() +
Student "\nStudent number: " + stdNb;
}
- studentNumber : int
+ Student()
+ Student(String, int) public String toString() {
return super.toString() +
+ reset(String, int) : void
"\nLevel: " + level;
+ getStudentNumber() : int }
+ setStudentNumber(int) : void
+ toString() : String
+ equals(Object) : boolean
extends
Undergraduate
- level : int
+ Undergraduate() Because the toString()
+ Undergraduate(String, int, int)
+ reset(String, int, int) : void method is overridden
+ getLevel() : int
+ setLevel(int) : void
+ toString() : String
+ equals(Object) : boolean
Copyright © 2010
Person
- name : String
+ Person() How come we do not use super to call
+ setName(String) : void the reset() method of the parent class?
+ getName() : String
+ toString() : String
+ equals(Object) : boolean public void reset(String newName, int newStdNb) {
extends setName(newName);
Student setStdNb(newStdNb);
}
- studentNumber : int
+ Student()
+ Student(String, int)
+ reset(String, int) : void
+ getStudentNumber() : int public void reset(String newName, int newStdNb, int newLevel) {
+ setStudentNumber(int) : void reset(newName, newStdNb);
+ toString() : String setLevel(newLevel); // Checks 1 <= newLevel <= 4
}
+ equals(Object) : boolean
extends
Undergraduate
- level : int
+ Undergraduate() Because the reset()
+ Undergraduate(String, int, int)
+ reset(String, int, int) : void method is overloaded
+ getLevel() : int
+ setLevel(int) : void
+ toString() : String
+ equals(Object) : boolean
Copyright © 2010
Overloading / Overriding…recap
Overloading:
Method overloading in Java occurs when two or more methods in the same class
have the exact same name but different parameters:
• Number of parameters is different.
• Or type of parameters is different.
Copyright © 2010
Overloading / Overriding…recap
Overriding:
Method overriding in Java occurs when a derived class requires a different
definition for an inherited method. Overriden methods have the exact same
name, return type, number of parameters and parameter types.
Copyright © 2010