Date post: | 01-Jan-2016 |
Category: |
Documents |
Upload: | marshall-walter |
View: | 33 times |
Download: | 8 times |
Chapter 11: Inheritance and Chapter 11: Inheritance and PolymorphismPolymorphism
JJavaava PProgramming:rogramming:
From Problem Analysis to Program From Problem Analysis to Program Design,Design, Second EditionSecond Edition
Java Programming: From Problem Analysis to Program Design, Second Edition 2
Chapter Objectives Learn about inheritance. Learn about subclasses and superclasses. Explore how to override the methods of a superclass. Examine how constructors of superclasses and subclasses
work. Learn about polymorphism. Examine abstract classes. Become aware of interfaces. Learn about composition.
Java Programming: From Problem Analysis to Program Design, Second Edition 3
Inheritance Inheritance lets you create new classes from
existing classes. Any new class that you create from an existing class
is called a subclass or derived class. existing classes are called superclasses or base
classes. The subclass inherits the properties of the superclass.
Rather than create completely new classes from scratch.
you can take advantage of inheritance and reduce software complexity.
Java Programming: From Problem Analysis to Program Design, Second Edition 4
Inheritance Single inheritance:
Subclass is derived from one existing class (superclass).
Multiple inheritance: Subclass is derived from more than one
superclass. Not supported by Java. In Java, a class can only extend the definition of
one class.
Java Programming: From Problem Analysis to Program Design, Second Edition 5
Inheritance
modifier(s) class ClassName extends ExistingClassName modifier(s){ memberList}
Java Programming: From Problem Analysis to Program Design, Second Edition 6
Inheritance: class Circle Derived from class Shape
public class Circle extends Shape{ . . .}
Java Programming: From Problem Analysis to Program Design, Second Edition 7
Inheritance1. The private members of the superclass are private to the
superclass.
2. The subclass can directly access the public members of the superclass.
3. The subclass can include additional data and method members.
4. The subclass can override (redefine) the public methods of the superclass. However, this redefinition applies only to the objects of the subclass, not to the objects of the superclass.
5. All data members of the superclass are also data members of the subclass. Similarly, the methods of the superclass (unless overridden) are also the methods of the subclass. (Remember Rule 1 when accessing a member of the superclass in the subclass.)
Java Programming: From Problem Analysis to Program Design, Second Edition 8
Using Methods of the Superclass in a Subclass
The subclass can give some of its methods the same name as given by the superclass.
To override a public method of the superclass in the subclass, the corresponding method in the subclass must have the same name, the same type, and the same formal parameter list.
If the corresponding method in the superclass and the subclass has the same name but different parameters, then this is method overloading in the subclass, which is also allowed.
Java Programming: From Problem Analysis to Program Design, Second Edition 9
UML Class Diagram: class Rectangle
Java Programming: From Problem Analysis to Program Design, Second Edition 10
UML Class Diagram: class Box
Java Programming: From Problem Analysis to Program Design, Second Edition 11
Inheritance
When writing a method’s definition of a subclass, to specify a call to the public method of the superclass: If subclass overrides public method of
superclass, specify call to public method of superclass:
super.MethodName(parameter list) If subclass does not override public method of
superclass, specify call to public method of superclass:
MethodName(parameter list)
Java Programming: From Problem Analysis to Program Design, Second Edition 12
class Boxpublic void print(){ super.print(); System.out.print("; Height = " + height);}public void setDimension(double l, double w, double h){ super.setDimension(l, w); if (h >= 0) height = h; else height = 0;}public double area(){ return 2 * (getLength() * getWidth() + getLength() * height + getWidth() * height);}
Java Programming: From Problem Analysis to Program Design, Second Edition 13
Defining Constructors of the Subclass A constructor typically serves to initialize instance variables.
When we instantiate a subclass object, this object inherits the instance variables of the superclass
but the subclass object cannot directly access the private instance variables of the superclass.
As a consequence, the constructors of the subclass can (directly) initialize only the instance variables of the subclass.
When a subclass object is instantiated, to initialize the (private) instance variables it must also automatically execute one of the constructors of the superclass.
Java Programming: From Problem Analysis to Program Design, Second Edition 14
Defining Constructors of the Subclass
Call to constructor of superclass: Must be first statement. Specified by super parameter list. If a constructor does not explicitly invoke a superclass
constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
public Box(){ super(); height = 0;}
public Box(double l, double w, double h){ super(l, w); height = h;}
Java Programming: From Problem Analysis to Program Design, Second Edition 15
Objects myRectangle and myBox
Rectangle myRectangle = new Rectangle(5, 3);Box myBox = new Box(6, 5, 4);
Java Programming: From Problem Analysis to Program Design, Second Edition 16
Protected Members of a ClassMembers of a class are classified into three categories :
Public
Private
Protected
So, If a member of a superclass needs to be accessed in a subclass, and still prevent its direct access outside the class ,that member is declared using the modifier protected.
Java Programming: From Problem Analysis to Program Design, Second Edition 17
Protected Members of a Class
Java Programming: From Problem Analysis to Program Design, Second Edition 18
Protected Members of a Class
public void setData(char ch, double v, int a){ super.setData(v); bCh = ch; //initialize bCh using the
//assignment statement dA = a;}
Java Programming: From Problem Analysis to Program Design, Second Edition 19
Protected Members of a Class
Dclass objects can not directly access bCh.
DClass dObject = new DClass;
dObject.bCh = ‘&’;
Java Programming: From Problem Analysis to Program Design, Second Edition 20
Protected Members of a Class
In an inheritance hierarchy, the public and protected members of a superclass are directly accessible, in a subclass, across any number of generations, that is, at any level and they are also accessible by methods of other classes in the same package.
Java Programming: From Problem Analysis to Program Design, Second Edition 21
Protected Members of a Class
Even though the public and protected data members of a super class are directly accessible in a subclass, in the inheritance hierarchy, it should be the responsibility of the superclass to properly initialize these data members.
Java Programming: From Problem Analysis to Program Design, Second Edition 22
The class Object In ch8 we have seen the method toString The default definition of the method toString
returns the class name followed by the hash code of the object.
Where is the method toString definied?
Java Programming: From Problem Analysis to Program Design, Second Edition 23
The class Object The method toString comes from the class Object, and it is a public member of this class.
In Java, if you define a class and do not use the reserved word extends to derive it from an existing class, then the class you define is automatically considered to be derived from the class Object.
The class Object directly or indirectly becomes the superclass of every class in Java.
Java Programming: From Problem Analysis to Program Design, Second Edition 24
The class Object: Equivalent Definition of a Class
public class Clock{//Declare instance variables as given in Chapter 8
//Definition of instance methods as given in Chapter 8
//...}public class Clock extends Object{//Declare instance variables as given in Chapter 8
//Definition of instance methods as given in Chapter 8
}
Java Programming: From Problem Analysis to Program Design, Second Edition 25
The class Object Using the mechanism of inheritance, public
members of class Object can be overridden and/or invoked by object of any class type.
Because every Java class is directly or indirectly derived from the class Object, it follows that the method toString becomes a public member of every Java class. Therefore, if a class does not override this method, whenever this method is invoked, the method’s default definition executes.
Java Programming: From Problem Analysis to Program Design, Second Edition 26
Some Constructors and Methods of the class Object
Java Programming: From Problem Analysis to Program Design, Second Edition 27
Hierarchy of Java Stream Classes
Java Programming: From Problem Analysis to Program Design, Second Edition 28
Polymorphism
Java allows us to treat an object of a subclass as an object of its superclass. In other words, a reference variable of a superclass type can point to an object of its subclass.
There are situations when this feature of Java can be used to develop generic code for a variety of applications.
Java Programming: From Problem Analysis to Program Design, Second Edition 29
Polymorphism
Person name, nameRef; //Person is the superclass
PartTimeEmployee employee,employeeRef;//PartTimeEmployee //is the subclass
name = new Person("John", "Blair");
employee = new PartTimeEmployee("Susan", "Johnson",
12.50, 45);
nameRef = employee;
System.out.println("nameRef: " + nameRef);
nameRef: Susan Johnson wages are: $562.5
Java Programming: From Problem Analysis to Program Design, Second Edition 30
Polymorphism
Subclass objects can be treated as superclass objects. This makes sense because the subclass has members corresponding to each of the superclass members.
Assignment in the other direction is not allowed because assigning a superclass object to a subclass reference would leave the additional subclass members undefined.
Java Programming: From Problem Analysis to Program Design, Second Edition 31
Polymorphism
Referring to a superclass object with a subclass reference is a syntax error.
Assigning a subclass object to a superclass reference, and then attempting to reference subclass-only members with the superclass reference , is a syntax error.
Java Programming: From Problem Analysis to Program Design, Second Edition 32
PolymorphismEven though nameRef is declared as a reference variable
of the type Person when the statement
System.out.println("nameRef: " + nameRef);
Excutes to output nameRef,the method toString of the class PartTimeEmployee executes.
This is called late binding, dynamic binding, or run-time binding; that is the method to be executed is determined at execution time, not compile time.
Java Programming: From Problem Analysis to Program Design, Second Edition 33
Polymorphism
In a class hierarchy, several methods may have the same name and
the same formal parameter list. Moreover, a reference variable of a class can
refer to either an object of its own class or an object of its subclass.
Therefore, a reference variable can invoke a method of its own class or of its subclass(es).
Java Programming: From Problem Analysis to Program Design, Second Edition 34
Polymorphism
Binding means associating a method definition with its invocation. In early binding, a
method’s definition is associated with its invocation when the code is compiled. In late
binding, a method’s definition is associated with the method’s invocation at execution
time. Java uses late binding for all methods
Java Programming: From Problem Analysis to Program Design, Second Edition 35
Polymorphism The term polymorphism means to assign multiple
meanings to the same method name. In Java, polymorphism is implemented using late
binding. The reference variable name or nameRef can
point to any object of the class Person or the class PartTimeEmployee.
These reference variables have many forms, that is, they are polymorphic reference variables. They can refer to objects of their own class or to objects of the classes inherited from their class.
Java Programming: From Problem Analysis to Program Design, Second Edition 36
Polymorphism Example
Superclass: Quadrilateral (رباعي)
Subclasses: Rectangle, Square, Parallelograms, Trapezoids.
An operation (such as calculating the area) that can be performed on an object of class Quadrilateral can also be performed on an object of class Rectangle. Such operations can also be performed on other kinds of Quadrilateral .
When a request is made through a superclass reference to use a method, Java chooses the correct overridden method polymorphically in the appropriate subclass associated with the object.
Java Programming: From Problem Analysis to Program Design, Second Edition 37
final You can declare a method of a class final using the keyword final.
For example, the following method is final.
public final void doSomeThing(){
//...}
If a method of a class is declared final, it cannot be overridden with a new definition in a derived class.
In a similar manner, you can also declare a class final using the keyword final.
If a class is declared final, then no other class can be derived from this class.
Java does not use late binding for methods that are private, marked final, or static.
Java Programming: From Problem Analysis to Program Design, Second Edition 38
Polymorphism You cannot automatically make reference variable of
subclass type point to object of its superclass. This is a syntax error
An explicit cast can be used to convert a superclass reference to a subclass reference.
This can only be done when the superclass reference is actually referencing (pointing to) a subclass object.
If a subclass object has been assigned to a reference of its superclass, it is acceptable to cast that object back to its own type. This must be done in order to send that object any of its messages that do not appear in the superclass.
Java Programming: From Problem Analysis to Program Design, Second Edition 39
Polymorphism
Suppose that supRef is a reference variable of a superclass type. Moreover, suppose that supRef points to an object of its subclass.
You can use an appropriate cast operator on supRef and make a reference variable of the subclass point to the object.
On the other hand, if supRef does not point to a subclass object and you use a cast operator on supRef to make a reference variable of the subclass point to the object, then Java will throw a ClassCastException—indicating that the class cast is not allowed.
Java Programming: From Problem Analysis to Program Design, Second Edition 40
Polymorphism
Person name, nameRef; //Person is the superclass
PartTimeEmployee employee,employeeRef;//PartTimeEmployee //is the subclass
name = new Person("John", "Blair");
employee = new PartTimeEmployee("Susan", "Johnson",
12.50, 45);
nameRef = employee;
Java Programming: From Problem Analysis to Program Design, Second Edition 41
Polymorphism
employeeRef = (PartTimeEmployee) name;
will throw a ClassCastException because name points to an object of the class Person.
However, the following statement is legal:employeeRef = (PartTimeEmployee) nameRef;
Java Programming: From Problem Analysis to Program Design, Second Edition 42
Polymorphism
Operator instanceof: Determines whether a reference variable that points to an object is of a particular class type.
p instanceof BoxShape
This expression evaluates to true if p points to an object of the class BoxShape; otherwise it evaluates to false:
Java Programming: From Problem Analysis to Program Design, Second Edition 43
Abstract Methods
A method that has only the heading with no body. Must be declared abstract.
public void abstract print();
public abstract object larger(object,
object);
void abstract insert(int insertItem);
Java Programming: From Problem Analysis to Program Design, Second Edition 44
Abstract Classes
A class that is declared with the reserved word abstract in its heading.
An abstract class can contain instance variables, constructors, finalizers, and non-abstract methods.
An abstract class can contain abstract methods. If a class contains an abstract method, the class must be
declared abstract. You cannot instantiate an object of an abstract class type.
You can only declare a reference variable of an abstract class type.
You can instantiate an object of a subclass of an abstract class, but only if the subclass gives the definitions of all the abstract methods of the superclass.
Java Programming: From Problem Analysis to Program Design, Second Edition 45
Abstract Class Examplepublic abstract class AbstractClassExample{ protected int x; public void abstract print();
public void setX(int a) { x = a; }
public AbstractClassExample() { x = 0; }}
Java Programming: From Problem Analysis to Program Design, Second Edition 46
Interfaces
A class that contains only abstract methods and/or named constants.
We have seen the Actionlistener in ch6. The WindowListener to handel winow events The MouseListener to handel mouse events
Java Programming: From Problem Analysis to Program Design, Second Edition 47
Interfaces
Why does Java have these interfaces? After al they are also classes!
Java Programming: From Problem Analysis to Program Design, Second Edition 48
Interfaces
The answer: Java doesn’t support multiple inheritance. A java program might have a variety of GUI
component that generate a variety of events. These events are handeled by separate interfaces. Therefore program might need to use more than one
such interface.
Java Programming: From Problem Analysis to Program Design, Second Edition 49
Interfaces The mechanism that was used in ch6 to handle an
event is inner class mechanism . Rather than using inner class mechanism, the class
containing the java program canitself be created on top of an interface.
public class RectangleProgram extends JFrame implements ActionListener
{ //…}
We still have to register the listener by using the reference this
Java Programming: From Problem Analysis to Program Design, Second Edition 50
Interfaces
To be able to handle a variety of events, Java allows a class to implement more than one interface.
That is how Java implements multiple inheritance, which is not true multiple inheritance.
Java Programming: From Problem Analysis to Program Design, Second Edition 51
Some Interface Definitionspublic interface WindowListener{ public void windowOpened(WindowEvent e); public void windowClosing(WindowEvent e); public void windowClosed(WindowEvent e); public void windowIconified(WindowEvent e); public void windowDeiconified(WindowEvent e); public void windowActivated(WindowEvent e); public void windowDeactivated(WindowEvent e);}
public interface ActionListener{ public void actionPerformed(ActionEvent e);}
Java Programming: From Problem Analysis to Program Design, Second Edition 52
Composition
Another way to relate two classes. One or more members of a class are objects of
another class type. “has-a” relation between classes.
For example, “every person has a date of birth.” relation between classes In inheritance was “ is-a”
relation For example, “every Employee is a person.”
Java Programming: From Problem Analysis to Program Design, Second Edition 53
Chapter Summary
Inheritance: Single and multiple Rules Uses Superclasses/subclasses (objects) Overriding/overloading methods Constructors
The class Object
Java Programming: From Problem Analysis to Program Design, Second Edition 54
Chapter Summary
Java stream classes Polymorphism Abstract methods Abstract classes Interfaces Composition