0% found this document useful (0 votes)
7 views56 pages

10-Inheritance & Polymorphism

The document discusses object-oriented programming concepts, focusing on inheritance and polymorphism as outlined in Chapter 11 of 'Introduction to Java Programming' by Y. Daniel Liang. It explains the relationships between superclasses and subclasses, the use of the 'super' keyword, method overriding, and the principles of polymorphism and dynamic binding. Key points include the importance of constructors, the distinction between overriding and overloading methods, and the role of the Object class in Java.

Uploaded by

husbanfaisal6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views56 pages

10-Inheritance & Polymorphism

The document discusses object-oriented programming concepts, focusing on inheritance and polymorphism as outlined in Chapter 11 of 'Introduction to Java Programming' by Y. Daniel Liang. It explains the relationships between superclasses and subclasses, the use of the 'super' keyword, method overriding, and the principles of polymorphism and dynamic binding. Key points include the importance of constructors, the distinction between overriding and overloading methods, and the role of the Object class in Java.

Uploaded by

husbanfaisal6
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object-Oriented Problem Solving

Inheritance & Polymorphism


Based on Chapter 11 of “Introduction to Java
Programming” by Y. Daniel Liang.

Eng. Asma Abdel Karim


Computer Engineering Department
Outline
• Superclasses and Subclasses (11.2)
• Using the Super keyword (11.3)
• Overriding Methods (11.4)
• Overriding vs. Overloading (11.5)
• The Object Class and its toString() (11.6)
• Polymorphism (11.7)
• Dynamic Binding (11.8)
• Casting Objects (11.9)
• The Object’s equals Method (11.10)
• The Protected Data and Methods (11.14)
• Preventing Extending and Overriding (11.15)
Eng. Asma Abdel Karim 2
Computer Engineering Department
Superclasses and Subclasses
• Classes are used to model objects of the same
type.
• Different classes may have some common
properties and behaviors.
• Inheritance allows you to:
– Define a generalized class that includes the common
properties and behavior.
– Define specialized classes that extend the generalized
class.
• Inherit the properties and methods from the general class.
• Add new properties and methods.

Eng. Asma Abdel Karim 3


Computer Engineering Department
Superclasses and Subclasses (Cont.)

• In Java terminology, a class C1 extended from


another class C2 is called a subclass, and C2 is
called a superclass.
– A superclass is also referred to as a parent class or a
base class, and a subclass as a child class, an extended
class, or a derived class.
• A subclass:
– inherits data fields and methods from its superclass
and,
– may also add new data fields and methods.

Eng. Asma Abdel Karim 4


Computer Engineering Department
Eng. Asma Abdel Karim 5
Computer Engineering Department
GeometricObject Class

Eng. Asma Abdel Karim 6


Computer Engineering Department
GeometricObject Class (Cont.)

Eng. Asma Abdel Karim 7


Computer Engineering Department
Circle Class

Eng. Asma Abdel Karim 8


Computer Engineering Department
Circle Class (Cont.)

Eng. Asma Abdel Karim 9


Computer Engineering Department
Rectangle Class

Eng. Asma Abdel Karim 10


Computer Engineering Department
Rectangle Class (Cont.)

Eng. Asma Abdel Karim 11


Computer Engineering Department
Comments
• The Circle class extends the GeometricObject using the following
syntax:

• The keyword extends tells the compiler that the Circle class extends
the GeometricObject class, thus inheriting the methods getColor,
setColor, isFilled, setFilled, and toString.
• The overloaded constructor Circle(double radius, String color,
boolean filled) is implemented by invoking the setColor and setFilled
methods to set the color and filled properties.
– These two public methods are defined in the superclass
GeometricObject and are inherited in Circle, so they can be used in the
Circle class.

Eng. Asma Abdel Karim 12


Computer Engineering Department
Comments (Cont.)
• You might attempt to use the data fields color and filled
directly in the constructor as follows:

• This is wrong, because the private data fields color and


filled in the GeometricObject class cannot be accessed
in any class other than in the GeometricObject class
itself.
– The only way to read and modify color and filled is through
their getter and setter methods.

Eng. Asma Abdel Karim 13


Computer Engineering Department
[Link]

Eng. Asma Abdel Karim 14


Computer Engineering Department
Important Notes Regarding Inheritance (1)

• Contrary to conventional interpretation, a


subclass is not a subset of its superclass.
– In fact, a subclass usually contains more
information and methods than its superclass.
• Private data fields in a superclass are not
accessible outside the class.
– They cannot be used directly in a subclass.
– They can only be accessed/mutated through
public accessors/mutators if defined in the
superclass.
Eng. Asma Abdel Karim 15
Computer Engineering Department
Important Notes Regarding Inheritance (2)
• Inheritance is used to model the is-a relationship.
– Do not blindly extend a class just for the sake of reusing
methods.
– For example, it makes no sense for a Tree class to extend a
Person class, even though they share common properties
such as height and weight.
• Some programming languages allow you to derive a
subclass from several classes.
– This capability is called multiple inheritance.
– Java does not allow multiple inheritance.
• A Java class may inherit directly from only one class.
– Multiple inheritance can be achieved through interfaces in
Java.

Eng. Asma Abdel Karim 16


Computer Engineering Department
The Super Keyword

• The keyword super refers to the superclass


and can be used to:
– Call a superclass constructor.
– Call a superclass method.

Eng. Asma Abdel Karim 17


Computer Engineering Department
Using the Super Keyword to Call a
Superclass Constructor
• Remember that a constructor is used to construct an
instance of a class.
• Unlike properties and methods, the constructors of a
superclass are not inherited by a subclass.
• They can only be invoked from the constructors of the
subclasses using the keyword super.
• The syntax to call a superclass’s constructor is:
– super(), or super(arguments);
– The statement super() invokes the no-arg constructor of its
superclass.
– The statement super(arguments) invokes the superclass
constructor that matches the arguments.

Eng. Asma Abdel Karim 18


Computer Engineering Department
Using the Super Keyword to Call a
Superclass Constructor: Example
• The statement super() or super(parameters)
must appear in the first line of the subclass’s
constructor.
• The following constructor can be added to the
Circle class of the previous example:
public Circle (double radius){
super(); Invokes the no-arg constructor,
which is the default constructor
[Link] = radius; of the GeometricObject class.
}

Eng. Asma Abdel Karim 19


Computer Engineering Department
Constructor Chaining
• A constructor may invoke an overloaded constructor
(using this) or its superclass constructor (using super).
• If neither is invoked explicitly, the compiler automatically
puts super() as the first statement in the constructor.

Eng. Asma Abdel Karim 20


Computer Engineering Department
Constructor Chaining (Cont.)
• In any case, constructing an instance of a class
invokes the constructors of all the superclasses along
the inheritance hierarchy.
– When constructing an object of a subclass, the subclass
constructor first invokes its superclass constructor before
Constructor Chaining

performing its own tasks.


– If the superclass is derived from another class, the
superclass constructor invokes its parent-class constructor
before performing its tasks.
– This process continues until the last constructor along the
inheritance hierarchy is called.

Eng. Asma Abdel Karim 21


Computer Engineering Department
Constructor Chaining: Example

Eng. Asma Abdel Karim 22


Computer Engineering Department
Constructor Chaining: Example (Cont.)

Eng. Asma Abdel Karim 23


Computer Engineering Department
Caution!!
• If a class is designed to be extended, it is better
to provide a no-arg constructor to avoid
programming errors.
• Example: this code cannot be compiled:
The default no-arg constructor of Apple
will try to invoke a no-arg constructor of
Fruit, which does not exist!

Eng. Asma Abdel Karim 24


Computer Engineering Department
Using the Super Keyword to Call a
Superclass Method
• The keyword super can be used to reference a method other
than the constructor in the superclass. The syntax is:
– [Link](parameters);
• You could rewrite the printCircle() method in the Circle class
as follows:

• It is not necessary to put super before getDateCreated() in


this case, however, because getDateCreated is a method in
the GeometricObject class and is inherited by the Circle class.
– Cases where the super keyword is needed to invoke the superclass
methods will be shown when methods overriding is introduced.
Eng. Asma Abdel Karim 25
Computer Engineering Department
Overriding Methods
• 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.
• The toString method in the GeometricObject class returns the
string representation of a geometric object.
• This method can be overridden to return the string
representation of a circle:

Should use the super keyword to invoke


the toSrting method of the superclass
Eng. Asma Abdel Karim GeometricObject. 26
Computer Engineering Department
Overriding Methods (Cont.)
• An instance method can be overridden only if it is
accessible.
– Thus, a private method cannot be overridden, because it is not
accessible outside its own class.
– If a method defined in a subclass is private in its superclass, the
two methods are completely unrelated.
• Like an instance method, a static method can be
inherited. However a static method cannot be
overridden.
– If a static method defined in the superclass is redefined in a
subclass, the method defined in the superclass is hidden.
– The hidden static methods can be invoked using the syntax
[Link].

Eng. Asma Abdel Karim 27


Computer Engineering Department
Overriding vs. Overloading
• Overloading means to define multiple methods with
the same name but different signatures.
• Overriding means to provide a new implementation
for a method in the subclass.
– The method should be defined in the subclass using the
same signature and the same return type.

Eng. Asma Abdel Karim 28


Computer Engineering Department
Overriding vs. Overloading: Example

Eng. Asma Abdel Karim 29


Computer Engineering Department
Overriding vs. Overloading: Notes
• Overridden methods are in different classes related
by inheritance; overloaded methods can be either in
the same class or different classes related by
inheritance.
• Overridden methods have the same signature and
return type; overloaded methods have the same
name but a different parameter list.

Eng. Asma Abdel Karim 30


Computer Engineering Department
Override Annotation
• To avoid mistakes, you can use a special Java syntax, called override
annotation:
– Place @Override before the method in the subclass.
• This annotation denotes that the annotated method is required to
override a method in the superclass.
– If a method with this annotation does not override its superclass’s
method, the compiler will report an error.
• For example, if toString is mistyped as tostring, a compile error is
reported. If the override annotation isn’t used, the compile won’t
report an error. Using annotation avoids mistakes.:

Eng. Asma Abdel Karim 31


Computer Engineering Department
The Object Class and Its toString() Method
• Every class in Java is descended from the
[Link] class.
• If no inheritance is defined when a class is defined,
the superclass of the class is Object by default.
• For example, the following two class definitions are
the same:

Eng. Asma Abdel Karim 32


Computer Engineering Department
The Object Class and Its toString() Method
(Cont.)
• One of the most important methods provided by the Object class is the
method toString.
• The signature of the toString method is:
– public String toString()
• Invoking toString() on an object returns a string that describes the
object.
– By default, it returns a string consisting of a class name of which the object
is an instance, an at sign (@), and the object’s memory address in
hexadecimal.
Circle c = new Circle();
[Link]([Link]());
– For example, the output of the following code is something like:
Circle@780324ff
– This message is not very helpful or informative.
– Usually you should override the toString method so that it returns a
descriptive string representation of the object.

Eng. Asma Abdel Karim 33


Computer Engineering Department
The Object Class and Its toString() Method
(Cont.)
• Usually, we override the toString method so that it returns a
descriptive string representation of the object.
• For example, the toString method in the Object class was
overridden in the GeometricObject class as follows:

• You can also pass an object to invoke


[Link](object) and [Link](object).
– This is equivalent to invoking
[Link]([Link]()) and
[Link]([Link]()).

Eng. Asma Abdel Karim 34


Computer Engineering Department
Polymorphism
• The three pillars of object-oriented programming are:
– Encapsulation
– Inheritance, and
– Polymorphism.
• The inheritance relationship enables a subclass to inherit
features from its superclass with additional new features.
• A class defines a type.
• A type defined by a subclass is called a subtype, and a type
defined by its superclass is called a supertype.
– Therefore, you can say that Circle is a subtype of GeometricObject
and GeometricObject is a supertype for Circle.
• A subclass is a specialization of its superclass; every
instance of a subclass is also an instance of its superclass,
but not vice versa.
– For example, every circle is a geometric object, but not every
geometric object is a circle.
Eng. Asma Abdel Karim 35
Computer Engineering Department
Polymorphism (Cont.)
• Polymorphism means that a variable of a supertype can
refer to a subtype object.
– You can always pass an instance of a subclass to a parameter of its
superclass type.
– An object of a subclass can be used wherever its superclass object
is used.

Eng. Asma Abdel Karim 36


Computer Engineering Department
Dynamic Binding
• A method can be implemented in several classes along
the inheritance chain.
– The JVM decides which method is invoked at runtime.
• A method can be defined in a superclass and
overridden in its subclass.
• For example, the toString() method is defined in the
Object class and overridden in GeometricObject.
Object o = new GeometricObject();
[Link]([Link]());
• Which toString() method is invoked by o?

Eng. Asma Abdel Karim 37


Computer Engineering Department
Dynamic Binding (Cont.)
• The type that declares a variable is called the variable’s
declared type.
– In the previous example, o’s declared type is Object.
– A variable of a reference type can hold a null value or a reference
to an instance of the declared type.
– The instance may be created using the constructor of the
declared type or its subtype.
• The actual type of the variable is the actual class for the
object referenced by the variable.
• Here o’s actual type is GeometricObject, because o references an
object created using new GeometricObject().
• Which toString() method is invoked by o is determined by
o’s actual type. This is known as dynamic binding.

Eng. Asma Abdel Karim 38


Computer Engineering Department
Dynamic Binding (Cont.)
• Suppose an object o is an instance of classes C1, C2, . . . , Cn-
1, and Cn, where C1 is a subclass of C2, C2 is a subclass of C3,
. . . , and Cn-1 is a subclass of Cn, as shown in the figure.
• That is, Cn is the most general class, and C1 is the most
specific class.
• In Java, Cn is the Object class.
• If o invokes a method p, the JVM searches for the
implementation of the method p in C1, C2, . . . , Cn-1, and Cn,
in this order, until it is found.
• Once an implementation is found, the search stops and the
first-found implementation is invoked.

Eng. Asma Abdel Karim 39


Computer Engineering Department
Eng. Asma Abdel Karim 40
Computer Engineering Department
Dynamic Binding (Cont.)
• Matching a method signature and binding a
method implementation are two separate issues.
• The declared type of the reference variable
decides which method to match at compile time.
• The compiler finds a matching method according
to the parameter type, number of parameters, and
order of the parameters at compile time.
• A method may be implemented in several classes
along the inheritance chain. The JVM dynamically
binds the implementation of the method at
runtime, decided by the actual type of the
variable.

Eng. Asma Abdel Karim 41


Computer Engineering Department
Casting Objects
• One object reference can be typecast into another object
reference.
– This is called casting object.
• 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 an instance
of Object.
• Suppose you want to assign the object reference o to a
variable of the Student type using the following statement:
Student b = o;
In this case a compile error would occur.
Eng. Asma Abdel Karim 42
Computer Engineering Department
Casting Objects (Cont.)
• The reason is that a Student object is always an
instance of Object, but an Object is not necessarily
an instance of Student.
• Even though you can see that o is really a Student
object, the compiler is not clever enough to know
it.
• To tell the compiler that o is a Student object, use
explicit casting.
– The syntax is similar to the one used for casting among
primitive data types.
– Enclose the target object type in parentheses and place
it before the object to be cast, as follows:
Student b = (Student)o; // Explicit casting
Eng. Asma Abdel Karim 43
Computer Engineering Department
Casting Objects (Cont.)
• It is always possible to cast an instance of a
subclass to a variable of a superclass (known as
upcasting).
– Because an instance of a subclass is always an
instance of its superclass.
• When casting an instance of a superclass to a
variable of its subclass (known as downcasting),
explicit casting must be used.
– To confirm your intention to the compiler with the
(SubclassName) cast notation.

Eng. Asma Abdel Karim 44


Computer Engineering Department
Casting Objects (Cont.)
• For the casting to be successful, you must make sure that the
object to be cast is an instance of the subclass.
• If the superclass object is not an instance of the subclass, a
runtime ClassCastException occurs.
– For example, if an object is not an instance of Student, it cannot
be cast into a variable of Student.
• It is a good practice, therefore, to ensure that the object is an
instance of another object before attempting a casting.
– This can be accomplished by using the instanceof operator.

Eng. Asma Abdel Karim 45


Computer Engineering Department
Why Casting is Necessary?
• You may be wondering why casting is necessary. The variable
myObject is declared Object.
• The declared type decides which method to match at
compile time.
– Using [Link]() would cause a compile error,
because the Object class does not have the getDiameter method.
– The compiler cannot find a match for [Link]().
• Therefore, it is necessary to cast myObject into the Circle
type to tell the compiler that myObject is also an instance of
Circle.
• Why not define myObject as a Circle type in the first place?
– To enable generic programming, it is a good practice to define a
variable with a supertype, which can accept an object of any
subtype.

Eng. Asma Abdel Karim 46


Computer Engineering Department
Casting and Polymorphism

Eng. Asma Abdel Karim 47


Computer Engineering Department
Comments
• The object member access operator (.) precedes the casting
operator.
– Use parentheses to ensure that casting is done before the .
operator, as in
((Circle)object).getArea();
• Casting a primitive type value is different from casting an
object reference.
– Casting a primitive type value returns a new value. For example:

– However, casting an object reference does not create a new


object. For example:

Eng. Asma Abdel Karim 48


Computer Engineering Department
The Object’s equals Method
• Another method defined in the Object class that is often
used is the equals method. Its signature is
public boolean equals(Object o)
• This method tests whether two objects are equal. The syntax
for invoking it is:
[Link](object2);
• The default implementation of the equals method in the
Object class is:
public boolean equals(Object obj) {
return (this == obj);
}
• This implementation checks whether two reference variables
point to the same object using the == operator.
• You should override this method in your custom class to test
whether two distinct objects have the same content.
Eng. Asma Abdel Karim 49
Computer Engineering Department
The Object’s equals Method (Cont.)
• The equals method is overridden in many classes in the Java
API, such as [Link] and [Link], to compare
whether the contents of two objects are equal.
• You can override the equals method in the Circle class to
compare whether two circles are equal based on their radius
as follows:
public boolean equals(Object o) {
if (o instanceof Circle)
return radius == ((Circle)o).radius;
else
return this == o;
}
• Using the signature equals(SomeClassName obj) (e.g.,
equals(Circle c)) to override the equals method in a subclass
is a common mistake. You should use equals(Object obj).
Eng. Asma Abdel Karim 50
Computer Engineering Department
The Protected Data and Methods
• So far you have used the private and public keywords to
specify whether data fields and methods can be
accessed from outside of the class.
• Private members can be accessed only from inside of
the class, and public members can be accessed from any
other classes.
• Often it is desirable to allow subclasses to access data
fields or methods defined in the superclass, but not to
allow non-subclasses to access these data fields and
methods.
• To accomplish this, you can use the protected keyword.
– This way you can access protected data fields or methods in
a superclass from its subclasses.
Eng. Asma Abdel Karim 51
Computer Engineering Department
The Protected Data and Methods (Cont.)

Eng. Asma Abdel Karim 52


Computer Engineering Department
The Protected Data and Methods (Cont.)

Eng. Asma Abdel Karim 53


Computer Engineering Department
Visibility Modifiers (Comments)
• Your class can be used in two ways:
(1) for creating instances of the class and
(2) for defining subclasses by extending the class.
• Make the members private if they are not intended for
use from outside the class.
• Make the members public if they are intended for the
users of the class.
• Make the fields or methods protected if they are
intended for the extenders of the class but not for the
users of the class.
• A subclass cannot weaken the accessibility of a method
defined in the superclass when overriding it.
– For example, if a method is defined as public in the
superclass, it must be defined as public in the subclass.
Eng. Asma Abdel Karim 54
Computer Engineering Department
Preventing Extending and Overriding
• You may occasionally want to prevent classes from
being extended.
• In such cases, use the final modifier to indicate
that a class is final and cannot be a parent class.
• The Math class is a final class. The String,
StringBuilder, and StringBuffer classes are also final
classes.

Eng. Asma Abdel Karim 55


Computer Engineering Department
Preventing Extending and Overriding
(Cont.)
• You also can define a method to be final; a final
method cannot be overridden by its subclasses.
• For example, the following method m is final
and cannot be overridden:

Eng. Asma Abdel Karim 56


Computer Engineering Department

You might also like