Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Object-Oriented Programming (CS F213)

Inheritance and Polymorphism

BITS Pilani
Hyderabad Campus
Agenda

• Inheritance
• Polymorphism

BITS Pilani, Hyderabad Campus


Inheritance
• It allows the creation of hierarchical classifications. Inheritance represents the IS-A relationship which
is also known as a parent-child relationship (for example, Apple is a Fruit, Car is a Vehicle).
• Using inheritance, you can create a general class that defines traits common to a set of related items.
This class can then be inherited by other, more specific classes, each adding those things that are
unique to it.
• When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
• In the terminology of Java, a class that is inherited is called a superclass. The class that does the
inheriting is called a subclass.
• A subclass is a specialized version of a superclass. It inherits all of the members defined by the
superclass and adds its own, unique elements

 Syntax of inheriting a superclass

BITS Pilani, Hyderabad Campus


Why Inheritance?

• For Method Overriding (so runtime polymorphism can be achieved).


• For Code Reusability.

BITS Pilani, Hyderabad Campus


Types of Inheritance supported by Java

Hierarchical
Single

Multilevel Note: Please note that Java does not support multiple
inheritance with classes. In java, we can achieve
multiple inheritance only through Interfaces.

BITS Pilani, Hyderabad Campus


Example of Single inheritance
class Animal{ Ouput:
void eat(){ barking…
System.out.println(“eating…”); eating…
}
class Dog extends Animal{
void bark(){
System.out.println(“barking…”);
}
}
class TestInheritance {
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}

BITS Pilani, Hyderabad Campus


Member Access and Inheritance

• Although a subclass includes all of the members of its superclass, it


cannot access the members of the superclass that have been declared
as private.

BITS Pilani, Hyderabad Campus


Note: Subclass has no
access to private
members of
superclass.

BITS Pilani, Hyderabad Campus


Example of Multilevel Inheritance

Output:
weeping…
barking…
eating…

BITS Pilani, Hyderabad Campus


Some Questions

1. ______ is a form of software reusability in which new classes acquire the members of existing
classes and embellish those classes with new capabilities.
Ans: Inheritance
2. When an object of a subclass is instantiated, a superclass ______ is called implicitly or explicitly.
Ans: constructor
3. State True or False: Superclass constructors are not inherited by subclasses.
Ans: True

BITS Pilani, Hyderabad Campus


Execution order of constructors in a class
hierarchy

In a class hierarchy, constructors complete their execution


in order of derivation, i.e., from superclass to subclass.

BITS Pilani, Hyderabad Campus


BITS Pilani, Hyderabad Campus
Example Program of Hierarchical Inheritance

BITS Pilani, Hyderabad Campus


Hierarchical Inheritance Examples

Superclass Subclasses

Student GraduateStudent, UndergraduateStudent

Shape Circle, Triangle, Rectangle, Rectangle,


Sphere, Cube
Loan CarLoan, HomeLoan, PersonalLoan

Employee Faculty, Staff

BITS Pilani, Hyderabad Campus


Role of super keyword

• In general, the constructor of subclass explicitly initializes the variables of


superclass. Here, initialization of superclass variables is done twice in general,
once in superclass and again by subclass. This repetition of code be avoided
by super keyword in subclass.
Use case:
• There will be times when you will want to create a superclass that keeps the
details of its implementation to itself (that is, that keeps its data members
private).
• Whenever a subclass needs to refer to its immediate superclass, it can do so
with the help of the keyword super.

BITS Pilani, Hyderabad Campus


Usage of super in two forms

1.To Call Superclass Constructors:


A subclass can call a constructor defined by its superclass by use of the following form of super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the superclass. super( ) must always
be the first statement executed inside a subclass’ constructor.
2. The second form of super acts somewhat like this keyword, except that super always refers to the
superclass of the subclass in which it is used.
This usage has the following general form:
super.member
Here, member can be either a method or an instance variable.
Note: The second form of super is most applicable to situations in which member names of a subclass hide
members by the same name in the superclass.

BITS Pilani, Hyderabad Campus


Usage of super to call superclass
constructors from subclass
class A{
int i, j;
A(int a1, int a2){
i=a1;
j=a2;
}
void displayTwo(){ Output:
System.out.println("i="+i+" j="+j);
} i=5 j=6 k=7
} i=5 j=6
class B extends A{
int k;
B(int a1, int a2, int a3){
super(a1,a2);//calls superclass constructor
k=a3;
}
void displayThree(){
System.out.println("i="+i+" j="+j+" k="+k);
}
}
class MainS{
public static void main(String args[]){
B obj=new B(5,6,7);
obj.displayThree();
obj.displayTwo();
}
} BITS Pilani, Hyderabad Campus
Usage of super to access superclass
variables in subclass

Output

BITS Pilani, Hyderabad Campus


What is the output?

class A{
int i, j;
}
class B extends A{ Output:
int j; 2 3
void display(){
super.i=j+1;
System.out.println(j+" "+i);
}
}
class MainExample{
public static void main(String args[]){
B obj=new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
BITS Pilani, Hyderabad Campus
Method Overriding

• When a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override
the method in the superclass. This is known method overriding.
• When an overridden method is called from within its subclass, it will always
refer to the version of that method defined by the subclass.
• The version of the method defined by the superclass will be hidden.

Note : A static, private, or final method and a constructor cannot be overridden.

BITS Pilani, Hyderabad Campus


Why Overridden Methods?

• Overridden methods allow Java to support run-time polymorphism.


• Method overriding allows a general class to specify methods that will be
common to all of its derivatives, while allowing subclasses to define the specific
implementation of some or all of those methods.

State True or False for the following:


When a subclass redefines a superclass method by using the same signature, the
subclass is said to overload that superclass method.
Ans:
False, This is known as overriding, not overloading (overloaded method has the
same name but a different signature).

BITS Pilani, Hyderabad Campus


Real world example of Method Overriding

BITS Pilani, Hyderabad Campus


What could be the output of the below code?
class Vehicle{
public void display(){
System.out.println("This is vehicle");
}
}
class Car extends Vehicle{ Output:
public void display(){ This is Car
System.out.println("This is Car"); This is Truck
}
}
class Truck extends Vehicle{
public void display(){
System.out.println("This is Truck");
}
}
class MainV{
public static void main(String args[])
{
Car c=new Car();
c.display();
Truck t=new Truck();
t.display();
}
} BITS Pilani, Hyderabad Campus
Differences between method
overloading and method overriding

Method Overloading Method Overriding

Method overloading is used to allow the Method overriding is used to provide the
object to call the same method by passing specific implementation of the method that is
varied number of values with different types. already provided by its superclass.
Method overloading is performed within a Method Overriding occurs in two classes that
class. have IS-A (inheritance) relationship.
In case method overloading, parameters must In case of Method overriding, parameters
be different (number of parameters, or their must be same.
types, order of parameters).
Method overloading is the example of compile Method overriding is the example of run time
time polymorphism polymorphism.

BITS Pilani, Hyderabad Campus


Polymorphism

• The word “polymorphism” means having many forms.


• The word “poly” means many and “morphs” means forms, So it means
many forms.
• It can be defined as a task that can perform a single action in different
ways.

In Java, polymorphism is mainly divided into two types:


1.Compile time Polymorphism (Also known as static binding). Method
overloading, which is discussed already.

2. Runtime Polymorphism (or Dynamic Method Dispatch or Dynamic


binding).
BITS Pilani, Hyderabad Campus
Compile time Polymorphism

It is also known as static polymorphism. This type of polymorphism is achieved


by function overloading (already discussed) or operator overloading.

Operator overloading: We can overload operators as well.


For example, the operator ‘+’ can be used to concatenate two strings.
Also, we know that the operator ‘+’ can also be used to add the values of two
operands.
Therefore, when ‘+’ is placed between integer operands, adds them and when
placed between string operands, concatenates them. The ‘+’ operator behaves
differently as per the context.

BITS Pilani, Hyderabad Campus


A Superclass Variable can Reference a
Subclass Object

• A reference variable of a superclass can be assigned a reference to any subclass


derived from that superclass. It is permissible to assign a subclass object to superclass
reference variable.
• In this context, it is important to understand that it is the type of the reference variable—
not the type of the object that it refers to that determines what members can be
accessed.
• If there is a overridden method in subclass, then superclass reference variable can
access overridden method. It is to be noted that superclass reference variable cannot
access attributes or instance variables of subclass.

In simple words: If there are some methods present in the superclass, but overridden
(same methods) by a subclass and assume that an object of subclass is created, and we
assign that object to the superclass reference variable, then we can use the superclass
reference variable to execute the overridden method defined in the subclass.

BITS Pilani, Hyderabad Campus


Dynamic Method Dispatch
 An Example program of
Dynamic Method Dispatch
(Runtime Polymorphism)
Important Points
• Def(Dynamic Method Dispatch): It is a process in which
call to the overridden method is resolved at runtime.

• When an overridden method is called through a


superclass reference, Java determines which version
of that method to execute based upon the type of the
object being referred to at the time the call occurs.

• Note: Upcasting is done when the parent class’s


reference variable refers to the object of the child class.
This is used in Runtime Polymorphism.

BITS Pilani, Hyderabad Campus


Question:
What is the output of the following program ?
class Human
{
void walk()
{
System.out.println("Can Run....");
}
}
class Student extends Human
{
void walk()
{
System.out.println("Running Fast...");
}
public static void main(String arg[])
{
Human p=new Student();
p.walk();
}
}

BITS Pilani, Hyderabad Campus


Solution:

Output – Running Fast…


Explanation : This question is based on Method Overriding. We create two
classes Human and Student; Human class extends student class feature and
overrides walk() method. We are calling the walk() method by the reference
variable of parent class. Since it refers to the subclass object, subclass
method is invoked at runtime.

BITS Pilani, Hyderabad Campus


What is the output of the below
program ?
class Problem
{
public void student()
{
System.out.println("student");
}
}
public class Derived extends Problem
{
public void student()
{
System.out.println("Problem");
}
public static void main(String[] args)
{
Derived obj = new Problem();
obj.student(); }
}

BITS Pilani, Hyderabad Campus


Solution :

Answer : Compilation error

Explanation :
A child class reference variable cannot be used to store an instance of parent class.

BITS Pilani, Hyderabad Campus


What is the output of the below program?

class A{
int i=10;
}
class B extends A{
int i=20;
}
public class Solution{
public static void main(String args[]){
A a=new B();
System.out.println(a.i);
}
}
Output:
10

Note: Superclass reference can access only the overridden methods of subclass and cannot
access the variables of subclass but can access its own variables.
BITS Pilani, Hyderabad Campus
What is the output of the below
program?

class A{
static void disp(){
System.out.println("Static method of class A ");
}
}
class B extends A{ Output:
static void disp(){ Static method of class A
System.out.println("Static method of class B");
} Note: Methods of both classes
} are static due to which the
class Main{ superclass reference variable
public static void main(String args[]) accesses its own static method
{ even though it is assigned the
A a=new B(); object of subclass B.
a.disp();
}
}
BITS Pilani, Hyderabad Campus
Abstract Class

• Abstract classes are classes for which we never intend to create objects.
• The purpose of abstract classes is to specify an abstract method in a superclass, that if it is extended
by a subclass, then the subclass must implement the abstract method (i.e., provide a method
definition).
• It is useful in situations where a superclass is unable to create a meaningful implementation for a
method. These methods would be specified by the abstract type modifier that need to be overridden
by subclasses who provide implementation for these methods..
• A class which is declared with the abstract keyword is known as an abstract class in Java.
To declare a class as abstract:
Use the abstract keyword in front of the class keyword.
To declare an abstract method:
abstract type method_name(parameter-list)
Note: Any class that contains one ore more abstract methods must be declared
as abstract.
BITS Pilani, Hyderabad Campus
Rules of abstract class

• Abstract classes cannot be instantiated, i.e., objects cannot be created with the new operator.
• Although abstract classes cannot be used to instantiate objects, but they can be used to create
object references, because Java’s approach to run-time polymorphism is implemented through the
use of superclass references.
• Abstract classes can have abstract methods (without body) and non-abstract methods (method with
the body).
• It can have constructors and static methods but no abstract static methods.
• Abstract methods of an abstract superclass must be implemented by subclasses. If the subclass
does not implement the abstract methods, then that class also must be declared as abstract itself.
• Abstract class cannot be final.

Notes: -When abstract specifier is applied to a class, then that class cannot be instantiated.
-When abstract specifier is applied to member function declaration, then that function should be
implemented in subclass.

BITS Pilani, Hyderabad Campus


Example program on Abstract Class

abstract class Animal{


public abstract void sound(); //abstract method without body
}
//Dog class extends Animal class
public class Dog extends Animal{

public void sound(){


System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}
}

Output:
Woof
BITS Pilani, Hyderabad Campus
Another example program on abstract class

BITS Pilani, Hyderabad Campus


Example of Abstract class with abstract
method and non-abstract method
abstract class MyClass{
public void disp(){
System.out.println("Concrete method of parent class");
}
abstract public void disp2();
}
class Example extends MyClass{
public void disp2()
{
System.out.println("abstract method of superclass implemented in subclass");
}
public static void main(String args[]){ Output:
Example obj = new Example(); abstract method of superclass implemented in subclass
obj.disp2(); Concrete method of parent class
obj.disp();
}
}
BITS Pilani, Hyderabad Campus
Example program that uses abstract class reference
variable to access overridden method

BITS Pilani, Hyderabad Campus


Aggregation (Has-a relationship) in
Java

• It represents “part-of” hierarchy and a directional


relationship.
• It represents a relationship between two separate classes.
• If a class has an entity reference, it is known as Aggregation.
• Aggregation represents HAS-A relationship.

Why aggregation?
• To maintain code re-usability.

BITS Pilani, Hyderabad Campus


Example of has-a relationship
class Emp {
class Address {  Part 1 of the int id;  Part 2 of the
String city,state,country; program String name; program
public Address(String city, String state, String country) { Address address;
this.city = city;
this.state = state; public Emp(int id, String
this.country = country; name,Address address) {
} this.id = id;
} this.name = name;
public static void main(String[] args) {
Address address1=new this.address=address;
 Part 3 of the }
Address("gzb","UP","india");
program
Address address2=new
Address("gno","UP","india"); void display(){
Emp e=new Emp(111,"varun",address1); System.out.println(id+" "+name);
Emp e2=new Emp(112,"arun",address2); System.out.println(address.city+"
e.display(); "+address.state+"
e2.display(); "+address.country);
} }
} BITS Pilani, Hyderabad Campus
Using final with Inheritance
Three uses of final keyword:
1. final can be used to create the equivalent of a named constant,
i.e., its value can’t be modified. For example, final int a=2;
2. final can be used to prevent Method Overriding.
3. final can be used to prevent Inheritance.

BITS Pilani, Hyderabad Campus


1. final to create name constants
• final variables must be used only for the values that we want to remain constant throughout the
execution of program.
• We must initialize a final variable, otherwise compiler will throw compile-time error.
• When to use final variables: They should be used only for the values that we want to remain constant
throughout the execution of program.

Example program:
class A{
final int CAPACITY=10;
}
class BFinal{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.CAPACITY);
obj.CAPACITY=20; //this will generate a compiler error.
}
} BITS Pilani, Hyderabad Campus
2. final to prevent method overriding
• There will be times when we will want to prevent it from occurring.
• To disallow a method from being overridden, specify final as a modifier at the start of its declaration.
• Methods declared as final cannot be overridden.

The following code segment illustrates the prevention of method overriding:

Compile-time error will be generated

BITS Pilani, Hyderabad Campus


3. Using final to prevent Inheritance
• It will be necessary to prevent a class from being inherited. To do so, precede the class declaration with
final.
• Declaring a class as final implicitly declares all of its methods as final, too.

The following code segment prevents inheritance and generates compile-time error if we try to inherit:

Note: It is illegal to declare a class as both abstract and final because an abstract class is incomplete
by itself and relies upon its subclasses to provide complete implementations.
BITS Pilani, Hyderabad Campus
Nested Classes

• Java allows us to define a class within another class. Such a class is called a nested class.
• A nested class is a member of its enclosing class (outer class).
Important Points:
• Nested classes are divided into two categories: non-static and static.
• Non-static nested classes are called inner classes.
• Nested classes that are declared static are called static nested classes.
• Non-static nested classes (inner classes) have access to other members of the enclosing class, even if
they are declared private.
• Static nested classes do not have access to other members of the enclosing class.
Example code with nested classes

BITS Pilani, Hyderabad Campus


Why Use Nested Classes?

• It is a way of logically grouping classes that are only used in one place: If a
class is useful to only one other class, then it is logical to embed it in that class
and keep the two together. Nesting such "helper classes" makes their package
more streamlined.
• It increases encapsulation: Consider two top-level classes, A and B, where B
needs access to members of A that would otherwise be declared private. By hiding
class B within class A, A’s members can be declared private and B can access
them. In addition, B itself can be hidden from the outside world.
• It can lead to more readable and maintainable code: Nesting small classes
within top-level classes places the code closer to where it is used.

BITS Pilani, Hyderabad Campus


Inner class

• An instance of InnerClass can exist only within an instance of OuterClass and has direct access to
the methods and fields of its enclosing instance.
• Also, because an inner class is associated with an instance, it cannot define any static members
itself.
Example code segment of inner class within outer class:

• To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object
within the outer object with this syntax:

BITS Pilani, Hyderabad Campus


Example program of Nested Class (Inner class within Outer class)
class Outer{
String so = ("This is Outer Class");
void display()
{
System.out.println(so);
}
void test(){
Inner inner = new Inner(); // inner class object is created within the scope of outer class instance.
inner.display();
}
//this is an inner class
class Inner{
String si =("This is inner Class");
void display(){
System.out.println(si);
} Output
} This is Outer Class
} This is inner Class
class Main{
public static void main(String args[]){
Outer outer = new Outer();
outer.display();
outer.test();
}
} BITS Pilani, Hyderabad Campus
Summary

• Inheritance
• Polymorphism
• Abstract Classes
• Nested Classes

BITS Pilani, Hyderabad Campus

You might also like