Lecture 3
Lecture 3
Programming II
2 - Inheritance and
Polymorphism(1)
1
Motivations
2
2– Inheritance and Polymorphism-
Outline
Superclasses and Subclasses
Overriding methods
3
2– Inheritance and Polymorphism-
Outline (cont.)
The ArrayList Class
Casting Objects
4
Inheritance
5
Inheritance
6
Superclasses and Subclasses
GeometricObject
-color: String The color of the object (default: white).
-filled: boolean Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date The date when the object was created.
+GeometricObject() Creates a GeometricObject.
+GeometricObject(color: String, Creates a GeometricObject with the specified color and filled
filled: boolean) values.
+getColor(): String Returns the color.
+setColor(color: String): void Sets a new color.
+isFilled(): boolean Returns the filled property.
+setFilled(filled: boolean): void Sets a new filled property.
+getDateCreated(): java.util.Date Returns the dateCreated.
+toString(): String Returns a string representation of this object.
Circle Rectangle
-radius: double -width: double
+Circle() -height: double
+Circle(radius: double) +Rectangle()
+Circle(radius: double, color: String, +Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double
+getRadius(): double color: String, filled: boolean)
+setRadius(radius: double): void +getWidth(): double
+getArea(): double +setWidth(width: double): void
+getPerimeter(): double +getHeight(): double
+getDiameter(): double +setHeight(height: double): void 7
+printCircle(): void +getArea(): double
+getPerimeter(): double
Defining a Subclass
8
Using the Keyword super
9
Overriding Methods in the
Superclass
A subclass inherits methods from a superclass.
Sometimes it is necessary for the subclass to modify the
implementation of a method defined in the superclass.
This is referred to as method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted
/** Override the toString method defined in GeometricObject */
public String toString() {
return super.toString() + "\nradius is " + radius;
}
}
10
Overriding vs. Overloading
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
A a = new A(); A a = new A();
a.p(10); a.p(10);
a.p(10.0); a.p(10.0);
} }
} }
class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }
11
Constructor between
Superclasses and Subclasses
Are superclass’s Constructor Inherited?
No. They are not inherited.
They are invoked explicitly or implicitly.
Explicitly using the super keyword.
A constructor is used to construct an instance of a class.
Unlike properties and methods, a superclass's
constructors are not inherited in the subclass. They can
only be invoked from the subclasses' constructors, using
the keyword super.
If the keyword super is not explicitly used, the
superclass's no-arg constructor is automatically
invoked.
12
The Object Class and Its
Methods
Every class in Java is descended from the
java.lang.Object class. If no inheritance is specified
when a class is defined, the superclass of the class is
Object.
13
Constructor between
Superclasses and Subclasses
Superclass’s Constructor Is Always Invoked
A constructor may invoke an overloaded constructor or
its superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first
statement in the constructor.
For example :
public A() { public A() {
is equivalent to
} super();
}
14
Constructor between
Superclasses and Subclasses
CAUTION : You must use the keyword super to call the
superclass constructor. Invoking a superclass
constructor’s name in a subclass causes a syntax error in
Java.
Java requires that the statement that uses the keyword
super appear first in the constructor.
15
Constructor Chaining
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
16
Trace Code
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty(); 1. Start from the
} main method
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
} 17
Trace Code
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty(); 2. Invoke Faculty
} constructor
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
} 18
Trace Code
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
} 3. Invoke Employee’s no-
class Employee extends Person {
arg constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
} 19
Trace Code
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
4. Invoke Employee(String)
class Employee extends Person { constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
} 20
Trace Code
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
} 5. Invoke Person() constructor
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
} 21
Trace Code
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
6. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
} 22
Trace Code
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
7. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
} 23
Trace Code
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
9. Execute println
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
} 24
The Object Class and Its
Methods
Every class in Java is descended from the
java.lang.Object class. If no inheritance is specified
when a class is defined, the superclass of the class is
Object.
25
The toString() method in
Object Class
The toString() method returns a string representation of
the object. The default implementation returns a string
consisting of a class name of which the object is an
instance, the at sign (@), and a number representing this
object.
For example:
Loan loan = new Loan();
System.out.println(loan.toString());
The example code displays something like Loan@15037e5 .
Usually you should override the toString() method so that it
returns a digestible string representation of the object.
26
Polymorphism
27
Polymorphism, Dynamic Binding
and Generic Programming
public class DynamicBindingDemo {
public static void main(String[] args) { Method m takes a parameter of the Object
m(new GraduateStudent()); type. You can invoke it with any object.
m(new Student());
m(new Person());
m(new Object());
}
An object of a subtype can be used
wherever its supertype value is required.
public static void m(Object x) { This feature is known as polymorphism.
System.out.println(x.toString());
} When the method m(Object x) is
} executed, the argument x’s toString()
class GraduateStudent extends Student { method is invoked. x may be an
} instance of GraduateStudent, Student,
Person, or Object. Classes
class Student extends Person {
GraduateStudent, Student, Person, and
public String toString() {
return "Student"; Object have their own implementation
} of the toString() method. Which
} implementation is used will be
class Person extends Object {
determined dynamically by the Java
public String toString() { Virtual Machine at runtime. This
return "Person"; capability is known as dynamic binding.
}
} 28
Dynamic Binding
Cn Cn-1 ..... C2 C1
30
Method Matching vs. Binding
(cont’d)
Whether a method can be invoked literally on an instance
is a syntax issue – matching the method invocation to some
method signature
boolean isInClass = ……
GeometricObject b = isInClass? New Circle() : new Rectangle();
b.setColor(“Blue”);
whether b.setColor(“Blue”) is legal depends on if
GeometricObject has a method setColor(String)
When a method can be invoked, which implementation to
select is a sematic issue – binding a particular
implementation according to the instance that the
reference actually points to at runtime
whether to invoke the setColor in Circle or the setColor in
Rectangle depends on what kind of instance b points to
31
Generic Programming
public class DynamicBindingDemo { Polymorphism allows methods to
public static void main(String[] args) {
m(new GraduateStudent()); be used generically for a wide
m(new Student()); range of object arguments. This is
m(new Person());
m(new Object()); known as generic programming.
}
If a method’s parameter type is a
public static void m(Object x) {
System.out.println(x.toString());
superclass (e.g., Object), you may
} pass an object to this method of
}
any of the parameter’s subclasses
class GraduateStudent extends Student { (e.g., Student or String). When an
}
object (e.g., a Student object or a
class Student extends Person { String object) is used in the
public String toString() {
return "Student";
method, the particular
} implementation of the method of
}
the object that is invoked (e.g.,
class Person extends Object { toString()) is determined
public String toString() {
return "Person";
dynamically.
}
32
}
The ArrayList Class
You can create an array to store objects. But the array’s size is fixed
once the array is created. Java provides the ArrayList class that can be
used to store an unlimited number of objects.
java.util.ArrayList<E>
+ArrayList() Creates an empty list.
+add(o: E) : void Appends a new element o at the end of this list.
+add(index: int, o: E) : void Adds a new element o at the specified index in this list.
+clear(): void Removes all the elements from this list.
+contains(o: Object): boolean Returns true if this list contains the element o.
+get(index: int) : E Returns the element from this list at the specified index.
+indexOf(o: Object) : int Returns the index of the first matching element in this list.
+isEmpty(): boolean Returns true if this list contains no elements.
+lastIndexOf(o: Object) : int Returns the index of the last matching element in this list.
+remove(o: Object): boolean Removes the element o from this list.
+size(): int Returns the number of elements in this list.
+remove(index: int) : boolean Removes the element at the specified index.
+set(index: int, o: E) : E Sets the element at the specified index.
33
Generic Type
34
Differences and Similarities
between Arrays and ArrayList
35
The instanceof Operator
36
The equals Method
37
The equals Method
38
The protected Modifier
Visibility increases
39
Accessibility Summary
public
protected -
default - -
private - - -
40
Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }
package p2;
41
The final Modifier
42
Casting Objects
44
Casting from
Superclass to Subclass
Casting a reference does not change anything, especially not
the object pointed to by the reference. Roughly speaking, it
changes the class label of the object -- as if compiler invokes
the methods of the object according to the class label.
GeometricObject s = new Circle(); // s is created as a circle but now is labeled as GeometricObject
c.setRadius(1.0); // correct
s
GeometricObject
Shape
45
Casting from
Superclass to Subclass
Explicit casting must be used when casting an object
from a superclass to a subclass. This type of casting
may not always succeed.
Apple x = (Apple)fruit;
Orange x = (Orange)fruit;
An apple is a fruit, so you can always safely assign an
instance of Apple to a variable for Fruit. However, a
fruit is not necessarily an apple, so you have to use
explicit casting to assign an instance of Fruit to a
variable of Apple.
However, the fruit (the instance) can be a orange.
46
Casting from
Superclass to Subclass
public class Animal {
public void callme() {
System.out.println("In callme of Animal");
after casting {
public void callme()
48
Assignment 2
(Due date 30th Sept.)
Output:
1. If the input year is the year before (<) 2000, print the date as the following
format:
yyyy-mm-dd: (event name)
where the day(dd), the month(mm) and the year(yyyy) are printed with
numbers.
(e.g. 1999-03-24: meeting)
49
Assignment 2
(Due date 30th Sept.)
Scoring (Total 12%):
1. Correct and runnable program fulfills the Basic
Requirement (5%)
2. Well structured code and good code style (1%)
3. Suitable use of Overloading, String, Array (3%)
4. Use Inheritance, polymorphism correctly (3%)
50
Assignment 2
(Due date 30th Sept.)
To determine whether a year is a leap year, you can
follow these steps:
1. If the year is evenly divisible by 4, go to step 2.
Otherwise, go to step 5.
2. If the year is evenly divisible by 100, go to step 3.
Otherwise, go to step 4.
3. If the year is evenly divisible by 400, go to step 4.
Otherwise, go to step 5.
4. The year is a leap year (it has 366 days).
5. The year is not a leap year (it has 365 days).
51
Assignment 2
(Due date 30th Sept.)
The following is an example to calculate the day of a week:
1. Take the last two digits of the year.
2. Divide by 4, discarding any fraction.
3. Add the day of the month.
4. Add the month's key value: JFM AMJ JAS OND = 144 025 036
146
5. Subtract 1 for January or February of a leap year.
6. For a Gregorian date, add 6 for 2000's.
7. Add the last two digits of the year.
8. Divide by 7 and take the remainder.
Resulting in 1 is Sunday, the first day of the week, 2 is Monday,
and so on.
52