0% found this document useful (0 votes)
8 views75 pages

Lecture 20 21 22 Inheritance and Polymorphism

This document discusses inheritance in Java. It defines key concepts like subclass, superclass, and the use of the super keyword. Inheritance allows classes to reuse attributes and methods from a parent class. The document provides examples of inheritance hierarchies between classes like GeometricObject, Circle, and Rectangle. It also discusses important aspects of constructors in inheritance like constructor chaining, where constructors of superclasses are invoked from subclass constructors in order to initialize the object. The use of the super keyword and this() is explained with an example to demonstrate constructor chaining.

Uploaded by

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

Lecture 20 21 22 Inheritance and Polymorphism

This document discusses inheritance in Java. It defines key concepts like subclass, superclass, and the use of the super keyword. Inheritance allows classes to reuse attributes and methods from a parent class. The document provides examples of inheritance hierarchies between classes like GeometricObject, Circle, and Rectangle. It also discusses important aspects of constructors in inheritance like constructor chaining, where constructors of superclasses are invoked from subclass constructors in order to initialize the object. The use of the super keyword and this() is explained with an example to demonstrate constructor chaining.

Uploaded by

Johny Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 75

Lecture-16

By
Dr. Bharati Mishra
Objectives
• Chapter 11
• Inheritance
• Subclass, superclass
• super keyword
• abstract keyword
• Overriding methods
• Polymorphism and dynamic binding
• final keyword
• ArrayList
Motivation
• Suppose you want to define classes to model
circles, rectangles, and triangles.
• These classes have many common features.
• What is the best way to design these classes so
to avoid redundancy?
• The answer is to use inheritance.
Inheritance
Superclass
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.
GeometricObject1
+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.
Circle4
Circle Rectangle
-radius: double -width: double
+Circle() -height: double
Rectangle1
+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
+setWidth(width: double): void
TestCircleRectangle
+getArea(): double
+getPerimeter(): double +getHeight(): double
+getDiameter(): double +setHeight(height: double): void
+printCircle(): void +getArea(): double
+getPerimeter(): double
Run
Inheritance
• Models “is-a” relationship
• Not all “is-a” relationships should be modeled
using inheritance
• For class A to extend class B, A should contain more
detailed information than B.
• Do not blindly extend a class just for the sake of
reusing methods!
Inheritance
• A subclass does not inherit the private members of
its parent class.
• A subclass is not a subset of the superclass
• Contains more information!
• Java does not support multiple inheritance
• It can be achieved through interfaces (an advanced
topic)
abstract
• An abstract class may or may not include abstract
methods.
• Abstract classes cannot be instantiated, but they
can be sub-classed.
• An abstract method is a method that is declared
without an implementation.
• If a class includes abstract methods, the class
itself must be declared abstract
abstract
• An abstract class example

public abstract class GraphicObject


{
// declare fields
// declare non-abstract methods
abstract void draw();
}
Inheritance & Constructor
Constructors
• Are superclass constructors inherited?
• No. Unlike properties and methods, a superclass's
constructors are not inherited in the subclass.
Constructors
1. The constructors are invoked either explicitly:
• Using the super keyword
2. Or implicitly:
• If the keyword super is not explicitly used, the
superclass's no-arg constructor is automatically
invoked.
Constructors
• 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.
Constructors
• Example
super
• The keyword super refers to the superclass of the
class in which super appears.
• This keyword can be used in two ways:
• To call a superclass constructor
• To call a superclass method
Constructors
• You must use the keyword super to call the
superclass constructor.
• Invoking a superclass constructor’s name in a
subclass causes a syntax error.
• Java requires that the statement that uses the
keyword super appear first in the constructor.
Chaining
• Constructor chaining
• Constructing an instance of a class invokes all the
superclasses’ constructors along the inheritance chain.
• This is called constructor chaining.
Chaining
Chaining
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 invoked");
}
}
Chaining
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 invoked");
}
}
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");
}
}
3. Invoke Employee’s
class Employee extends Person {
public Employee() {
no-arg constructor
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 invoked");
}
}
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");
}
}
4. Invoke
class Employee extends Person { Employee(String)
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 invoked");
}
}
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);
}
}
5. Invoke Person()
constructor
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor invoked");
}
}
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 { 6. Execute println


public Person() {
System.out.println("(1) Person's no-arg constructor invoked");
}
}
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);
}
}
7. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor invoked");
}
}
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 { 8. Execute println


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 invoked");
}
}
Chaining
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty(); 9. Execute println
}

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 invoked");
}
}
Chaining
• Chaining in the program:
Chaining
• Find out the errors in the program:
Subclass/Superclass
Subclass
• A subclass extends properties and methods
from the superclass.
• You can also:
• Add new properties
• Add new methods
• Override the methods of the superclass
Subclass
• You could rewrite the printCircle() method
in the Circle class as follows:
Overriding
Overriding
• 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.
Overriding
• Method overriding
Overriding
• An instance method can be overridden only
if it is accessible.
• Thus a private method cannot be
overridden.
• If a method defined in a subclass is private
in its superclass, the two methods are
completely unrelated.
Overriding
• 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.
Overriding
• Overriding vs. overloading
Object Class
Object Class
• 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.
Object Class
• Equivalent
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,
• (@),
• and a number representing this object.
Object Class

• The code displays something like


Loan@15037e5.
• This message is not very helpful or
informative.
• Usually you should override the toString
method so that it returns a digestible string
representation of the object.
Polymorphism
Polymorphism
• An object of a subtype can be used
wherever its supertype value is required.
• This feature is known as polymorphism.
Polymorphism
• Three pillars of OOP
1. Encapsulation
2. Inheritance
3. Polymorphism
Code
• Polymorphism
Code
• If polymorphism is used:
• Which implementation is used will be
determined dynamically by the Java Virtual
Machine at runtime.
• This capability is known as dynamic binding.
Code
Binding
• 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.
• That is, Cn is the most general class, and C1
is the most specific class.
• In Java, Cn is the Object class.
Binding
• If o invokes a method p, the JVM searches
the implementation for 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.
Binding
• Matching a method signature
• The compiler finds a matching method
according to parameter type, number of
parameters, and order of the parameters at
compilation time.
• Binding a method
• A method may be implemented in several
subclasses.
• The Java Virtual Machine dynamically binds
the implementation of the method at
runtime.
Generic Programming

• Polymorphism allows methods to be used


generically for a wide range of object
arguments.
• This is known as generic programming.
Binding
• If a method’s parameter type is a superclass
(e.g., Object), you may pass an object to
this method of any of the parameter’s
subclasses (e.g., Student or String).
• When an object (e.g., a Student object or a
String object) is used in the method, the
particular implementation of the method of
the object that is invoked (e.g., toString) is
determined dynamically.
Casting
Casting
• Casting can be used to convert an object of
one class type to another within an
inheritance hierarchy.
Casting
• The following statement causes a compilation
error:

• Because a Student object is always an


instance of Object, but an Object is not
necessarily an instance of Student!
Casting
• Explicit casting must be used when casting
an object from a superclass to a subclass.
• This type of casting may not always
succeed.
instanceof
• Use the instanceof operator to test
whether an object is an instance of a class.
Code
• This example creates two geometric
objects: a circle, and a rectangle. It displays
the area and diameter if the object is a
circle, and displays area if the object is a
rectangle.

TestPolymorphismCasting Run
Equality
equals()
• The equals() method compares the
contents of two objects.
• The default implementation of the equals
method in the Object class is as follows
equals()
• You can override equals() method in
your class
ArrayList
ArrayList
• 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.
ArrayList
• ArrayList

java.util.ArrayList
+ArrayList() Creates an empty list.
+add(o: Object) : void Appends a new element o at the end of this list.
+add(index: int, o: Object) : 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) : Object 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) : Object Removes the element at the specified index.
+set(index: int, o: Object) : Object Sets the element at the specified index.
Program
• ArrayList
• You will get a compilation warning
“unchecked operation.” Ignore it. This
warning can be fixed using generic types in
Chapter 20.

TestArrayList Run
Program
• MyStack MyStack

MyStack
-list: ArrayList A list to store elements.
+isEmpty(): boolean Returns true if this stack is empty.
+getSize(): int Returns the number of elements in this stack.
+peek(): Object Returns the top element in this stack.
+pop(): Object Returns and removes the top element in this stack.
+push(o: Object): void Adds a new element to the top of this stack.
+search(o: Object): int Returns the position of the first element in the stack from
the top that matches the specified element.
Accessibility
protected
• Another visibility modifier
• A protected data or a protected method in
a public class can be accessed by any class
in the same package or its subclasses
• Even if the subclasses are in a different
package.
Accessibility
• Accessibility summary

Modifier Accessed Accessed Accessed Accessed


on members from the from the from a from a different
in a class same class same package subclass package

public

protected -

default - -

private - - -
Accessibility
• Accessibility example
Accessibility
• A subclass may override a protected method
in its superclass and change its visibility to
public.
• However, a subclass cannot weaken the
accessibility of a method defined in the
superclass.
• For example, if a method is defined as public
in the superclass, it must be defined as
public in the subclass.
final keyword
final
• A final class cannot be extended

• A final variable is a constant

• A final method cannot be overridden by


its subclasses.

You might also like