Download Chapter 9: Objects and Classes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
Chapter 10 Inheritance and Polymorphism
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
2
OOP
• Encapsulation
• Inheritance
• Polymorphism
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
3
Motivations
We can create a class for each shape.
 i.e., Circles, Rectangles, Triangles
Many common features
Best class design to avoid redundancy?
Inheritance
subclass (Circle) can extend base class (Shape)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
4
Inheritance
• The inheritance hierarchy describes a
relationship between entities.
• A poodle is a dog, which is a mammal, which is
an animal.
• A poodle has the same properties as a dog and
can do anything a dog can do…
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
5
Inheritance
Syntax:
class Subclass extends Superclass
{
//subclass definition
}
Subclass inherits the interface of the superclass,
and can add to it.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
6
Keyword: super
How to access superclass?
keyword super refers to the superclass
super can be used:
• To call a superclass constructor
• To call a superclass method
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Are superclass’s Constructors
Inherited?
No. They are not inherited.
How to invoke superclass’s constructors?
Explicitly using the super keyword.
Implicitly call the no-arg constructor if it exists.
(Otherwise: compilation error)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
7
Superclass’s Constructor Is Always Invoked
Subclass’s constructor may invoke any of superclass’s
constructors.
If none invoked explicitly, super() inserted at beginning.
public A() {
}
public A(double d) {
// some statements
}
public A() {
super();
}
is equivalent to
is equivalent to
public A(double d) {
super();
// some statements
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
8
9
CAUTION
You must use the keyword super to call
the superclass constructor.
Syntax error: Invoking superclass’s
constructor by name in subclass.
Call to a superclass constructor must
appear first in constructor.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
10
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.
+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.
GeometricObject1
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Rectangle()
+getRadius(): double
+Rectangle(width: double, height: double)
+setRadius(radius: double): void
+getWidth(): double
+getArea(): double
+setWidth(width: double): void
+getPerimeter(): double
+getHeight(): double
+getDiameter(): double
+setHeight(height: double): void
Circle4
Rectangle1
TestCircleRectangle
+getArea(): double
+getPerimeter(): double
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Run
Constructor Chaining
Constructing an instance of a class invokes all the superclasses’ constructors
along the inheritance chain. This is called constructor chaining.
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");
}
}
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");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
11
animation
12
Trace Execution
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");
}
}
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");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
animation
13
Trace Execution
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");
}
}
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");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
animation
14
Trace Execution
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 noarg constructor
}
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");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
animation
15
Trace Execution
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)
constructor
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");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
animation
16
Trace Execution
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");
}
}
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);
}
}
5. Invoke Person() constructor
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
animation
17
Trace Execution
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");
}
}
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);
}
}
6. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
animation
18
Trace Execution
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");
}
}
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);
}
}
7. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
animation
19
Trace Execution
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");
}
}
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);
}
}
8. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
animation
20
Trace Execution
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");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Example on the Impact of a Superclass
without no-arg Constructor
Find the errors in the program:
public class Apple extends Fruit {
}
class Fruit {
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
21
22
Declaring a Subclass
Subclass extends superclass’s properties and methods.
It can also:

Add new properties

Add new methods

Override the methods of the superclass
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Calling Superclass Methods
You could rewrite the printCircle() method in the Circle class as
follows:
public void printCircle() {
System.out.println("The circle is created " +
super.getDateCreated() + " and the radius is " + radius);
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
23
Overriding Methods in the Superclass
24
Subclass inherits superclass methods.
Subclass can modify the implementation of superclass’s method.
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;
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
NOTE
Accessible instance methods can be
overridden.
Private method cannot be overridden
If subclass redefines a method that is
private in its superclass, the two methods
are completely unrelated.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
25
Overriding vs. Overloading
26
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
}
}
class B {
public void p(int i) {
}
}
class B {
public void p(int i) {
}
}
class A extends B {
// This method overrides the method in B
public void p(int i) {
System.out.println(i);
}
}
class A extends B {
// This method overloads the method in B
public void p(double i) {
System.out.println(i);
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
27
The Object Class and Its Methods
Every class in Java descends from
java.lang.Object
Default superclass of a class is Object.
public class Circle {
...
}
Equivalent
public class Circle extends Object {
...
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
The toString() method in Object
toString() method returns string representation of the
28
object. Default implementation (class Object) returns
object’s type, the at sign (@), and a number representing
this object.
Loan loan = new Loan();
System.out.println(loan.toString());
Output: Loan@15037e5
Not very informative!
Override the toString method …
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
29
Object Comparison
Comparing Objects:
Reference Equality (== operator)
vs.
Content Equality (equals method)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
30
The equals Method
The equals() method compares contents of two objects.
Default implementation (in Object):
public boolean equals(Object obj) {
return (this == obj);
}
Override to
compare
contents.
public boolean equals(Object o) {
if (o instanceof Circle) {
return radius == ((Circle)o).radius;
}
else
return false;
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
31
Polymorphism
• An object of a subtype can be used wherever its
supertype value is required. This feature is
known as polymorphism.
• The JVM does not know at compile time what
type the variable will refer to.
• Dynamic binding to locate appropriate method.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
32
Dynamic Binding
How does dynamic binding work?
Begins with lowest subclass,
Traces up inheritance hierarchy until a method definition
is found that matches the method call.
Once an implementation is found, the search stops and
the first-found implementation is invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
33
Generic Programming
• With polymorphism, methods can be used
generically for many different types of
arguments.
• Hence, the term generic programming.
• When a method is invoked, the particular
implementation is determined dynamically.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
34
Generic Programming Example
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Object x) {
System.out.println(x.toString());
}
}
class GraduateStudent extends Student {
}
class Student extends Person {
public String toString() {
return "Student";
}
}
class Person extends Object {
public String toString() {
return "Person";
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Casting Objects
We have casted variables of one primitive type to another.
Casting can convert an object of one class type to another
within an inheritance hierarchy. In the preceding section, the
statement
m(new Student());
assigns the object new Student() to a parameter of the Object
type. This statement is equivalent to:
Object o = new Student(); // Implicit casting
m(o);
The statement Object o = new Student(), known as
implicit casting, is legal because an instance of
Student is automatically an instance of Object.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
35
36
Why Casting Is Necessary?
To assign object reference o to variable of Student type:
Student b = o;
Compilation error!
How is this different than Object o = new Student() ?
• A Student object is always an instance of Object.
• An Object is not necessarily an instance of Student.
• You see that o is really a Student object; the compiler can’t.
• Explicit casting tells the compiler that o is a Student object.
Student b = (Student)o; // Explicit casting
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
37
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 y = (Orange)fruit;
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
38
The instanceof Operator
instanceof operator tests if an object is an instance of a class:
Object myObject = new Circle();
... // Some lines of code
/** Perform casting if myObject is an instance of
Circle */
if (myObject instanceof Circle) {
System.out.println("The circle diameter is " +
((Circle)myObject).getDiameter());
...
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
39
instanceof
Static Type
Vs.
Dynamic Type
Until now an object variable and its reference
were always of the same type.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
40
TIP
To help understand casting, you may also
consider the analogy of fruit, apple, and
orange with the Fruit class as the
superclass for Apple and Orange. 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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
41
Example: Demonstrating
Polymorphism and Casting
This example creates two geometric objects:
a circle, and a rectangle, invokes the
displayGeometricObject method to display
the objects. The displayGeometricObject
displays the area and diameter if the object
is a circle, and displays area if the object is a
rectangle.
TestPolymorphismCasting
Run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
42
The protected Modifier
• The protected modifier for data or methods
of a class.
• Protected data or method in public class can
be accessed by any class in the same package
or its subclasses, even if the subclasses are in
a different package.
• private, default, protected, public
Visibility increases
private, none (if no modifier is used), protected, public
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
43
Accessibility Summary
Modifier
on members
in a class
Accessed
from the
same class
Accessed
from the
same package
Accessed
from a
subclass
Accessed
from a different
package
public
-
protected
default
private
-
-
-
-
-
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
44
Visibility Modifiers
package p1;
public class C1 {
public int x;
protected int y;
int z;
private int u;
public class C2 {
C1 o = new C1();
can access o.x;
can access o.y;
can access o.z;
cannot access o.u;
protected void m() {
}
}
can invoke o.m();
}
package p2;
public class C3
extends C1 {
can access x;
can access y;
can access z;
cannot access u;
public class C4
extends C1 {
can access x;
can access y;
cannot access z;
cannot access u;
can invoke m();
}
public class C5 {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
cannot access o.u;
can invoke m();
}
cannot invoke o.m();
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
45
Subclass Cannot Weaken the Accessibility
A subclass may override a protected
method in its superclass and change its
visibility to public.
A subclass cannot weaken the
accessibility of a method defined in the
superclass.
(A method defined as public in the
superclass must be public in the subclass.)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
46
NOTE
Like an instance method, a static method
is inherited.
A static method cannot be overridden.
If a static method defined in the superclass
is redefined in a subclass, the superclass
method is hidden.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
47
Modifiers
Access specifier for overriding method can allow
more, but not less, access than the overridden
method.
(protected can become public, not private)
Compile-time error if attempt to change an
instance method in the superclass to a class
method in the subclass, and vice versa.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
48
Subclass method with same signature as Superclass's method
Superclass Instance
Method
Superclass Static
Method
Subclass Instance
Method
Overrides
Compilation Error
Subclass Static Method
Compilation Error
Hides
A subclass can overload a method of its superclass.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
49
The final Modifier
• The final class cannot be extended:
final class Math {
...
}
• The final variable is a constant:
final static double PI = 3.14159;
• The final method cannot be
overridden by its subclasses.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Immutable Objects and Classes
50
Immutable Object
• Contents cannot be changed after object is created
• Its class is an immutable class
If you delete the set method in our Circle class, the class would
be immutable - radius is private and cannot be changed
without a set method.
A class with all private data fields and no mutators is not
necessarily immutable. (Example: class Student has all private
data fields and no mutators, but it is mutable. Look at
getBirthDate method!)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Example
public class Student {
private int id;
private BirthDate birthDate;
51
public class BirthDate {
private int year;
private int month;
private int day;
public BirthDate(int newYear,
int newMonth, int newDay) {
year = newYear;
month = newMonth;
day = newDay;
}
public Student(int ssn,
int year, int month, int day) {
id = ssn;
birthDate = new BirthDate(year, month, day);
}
public int getId() {
return id;
}
public BirthDate getBirthDate() {
return birthDate;
}
}
public void setYear(int newYear) {
year = newYear;
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is changed!
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
52
What Class is Immutable?
Immutable Class
• All fields are private
• No mutators
• Methods can't be overridden (class or methods are
final)
• If a field isn't primitive or immutable, make a deep
clone on the way in and the way out.
Example: String class
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671