Вы находитесь на странице: 1из 28

CS 1101-03

Programming and Problem Solving

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);
}

class Demo { class Main {


int i; public static void main(String args[]) { 0 (without explicit constructor,
} Demo d = new Demo(); initialized with the default of the type).
System.out.println(d.i);
}

class Demo { class Main { 11 21


int i; public static void main(String args[]) {
int j; Demo d1 = new Demo(); d2 is a reference to the
Demo (){ Demo d2 = d1; same object as d1
i=10; d1.i +=1;
j=20; d1.j +=1;
} System.out.println(d2.i + “ “ + d2.j);
} }

hello world

The doSomething is a setter


(could be renamed setStr)

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.

From an external point of view, you are interested in :


- Starting the clock.
- Stopping the clock.
- Obtaining the elapsed time between.

How would you define a Watch class ?

Copyright © 2010
Static Fields
• Suppose you have a class Employee.
• How can you enforce that each employee has a unique ID.

We need to manage the id from the client side…


Although this is clearly a property of the
Every time we create a new Employee class
object Employee, the variable id
has the default value

We want a property in the Employee class that is stored at the


class level – not at the object level: that’s what a static field is.

Copyright © 2010
Static Fields

empCnt being static exists at the


Employee class level.

Each time a new object is created, empCnt


is incremented by 1

Static fields and/or methods are not copied into each object

Rather they are shared by all objects of that class

Copyright © 2010
Accessing Static Fields
• From inside the class where the field was
declared:
fieldName // get the value
fieldName = value; // set the value

• From another class (if the field is public):


ClassName.fieldName // get the value
ClassName.fieldName = value; // set the value

• Generally static fields are not public unless they


are final

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

It gives an excellent example of why encapsulation is important


so that we can later change how a class is implemented
without affecting its external behavior (and thus do not affect
anyone who is using the 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.

New classes can be derived from previously defined classes.


This will allow us to eliminate redundancy of re-creating instance
methods or variables across multiple classes.

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

To keep things simple, each student only has a


student number in addition to being a Person
Copyright © 2010
Derived class - example
public class Student extends Person { public void setStdNb(int newStdNb) {
private int stdNb; this.stdNb = newStdNb;
}
public Student() {
super(); // explained later public String toString() {
this.stdNb = 0; // no number yet return("Name: " + getName() +
} "\nStudent number: " + stdNb);
}
public Student(String initName,
int initStdNb) { public boolean equals(Object other) {
super(initName); if (other instanceof Student) {
setStdNb (iniStdNb); Student otherStudent = (Student)other;
} return (super.equals(otherStudent)
&& this.stdNb == otherStudent.stdNb);
public void reset(String newName, } else {
int newStdNb) { return false;
setName(newName); }
setStdNb(newStdNb); }
}

public int getStdNb() {


return this.stdNb;
}

Declare only the added instance variables and define


only the added and overridden methods
All Student objects are also Person
objects  they include a name field and The variables and methods of the base class which
we can call the setName() and are not declared private are inherited automatically.
getName() methods on them
Law Firm Employee Analogy

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

Polygon Ellipse Line

Pentagon Rectangle Triangle Circle

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() {

public Student(String initName,


int initStdNb) {

}
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){

public Person() { Student s = new Student();


name = "No name yet."; System.out.println (s.name);
} System.out.println (s.stdNb);
public Person(String initialName) { }
name = initialName; }
}
… What is the output ?
class Student extends Person {
int stdNb; No name yet.
public Student() {
10
stdNb = 10;

}
}

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
}

• Any use of this must be the first action in the constructor


definition
• Thus, a constructor definition cannot contain a call using super
and a call using this
• Advanced: To use both super and this…
• Include a call using this in the one constructor and a call using super
in the called constructor

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…!!!
}
...
}

However, you cannot repeat the use of super to invoke a method in


some ancestor class other than the immediate base class

E.g., you cannot do super.super.toString();

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.

int dateChange (int month) { int dateChange (int month) {


…. ….
} }
int dateChange (int year) { double dateChange (int year) {
…. ….
} }

int dateChange (int month) { int dateChange (int month) {


…. ….
} }
int dateChange (int month, int year) { int dateChange (String month) {
…. ….
} }

Overloading happens at Compile time.

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.

public class SuperClass {


int method () {
return 1000;
}
….
public class ChildClass extends SuperClass {
int method () {
return 2000;
}

Overriding happens at run time.

Copyright © 2010

Вам также может понравиться