0% found this document useful (0 votes)
14 views40 pages

Unit 2

Oops notes

Uploaded by

mmegala
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)
14 views40 pages

Unit 2

Oops notes

Uploaded by

mmegala
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
You are on page 1/ 40

23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

UNIT II INHERITANCE, ABSTRACT CLASSES AND INTERFACES


Overloading Methods - Inheritance: Basics – Types of Inheritance - Constructors and
Inheritance - Super keyword - Method Overriding – Dynamic Method Dispatch – Abstract
Classes and Methods – final keyword - Interfaces: Defining an interface – implementing an
interface – Multiple Inheritance through interface.

2.1 OVERLOADING METHODS

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases
the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of
two numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance
for calling methods.
1
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Output
22
33

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Output:

22
24.9

2
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

2.2 INHERITANCE

Inheritance can be defined as the procedure or mechanism of acquiring all the


properties and behaviors of one class to another, i.e., acquiring the properties and
behavior of child class from the parent class.
When one object acquires all the properties and behaviours of another object,
it is known as inheritance. Inheritance represents the IS-A relationship, also known
as parent-child relationship.
Uses of inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
Types of inheritance in java: single, multilevel and hierarchical inheritance. Multiple
and hybrid inheritance is supported through interface only.
Syntax:
class subClass extends superClass
{
//methods and fields
}

3
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

Terms used in Inheritence


 Class: A class is a group of objects which have common properties. It is a template
 or blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
 called a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits
 the features. It is also called a base class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism which facilitates
you to reuse the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in previous class.

SINGLE INHERITANCE
In Single Inheritance one class extends another class (one class only).
Example
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispA() method of ClassA
b.dispA();
//call dispB() method of ClassB
b.dispB();
}
}
Output :
disp() method of ClassA
disp() method of ClassB

4
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

Example
class Animal{
void eat(){System.out.println("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();
}}

Output:

barking...
eating...

MULTILEVEL INHERITANCE

In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived
class becomes the base class for the new class.
Example
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}

5
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispA() method of ClassA
c.dispA();
//call dispB() method of ClassB
c.dispB();
//call dispC() method of ClassC
c.dispC();
}
}
Output :
disp() method of ClassA
disp() method of ClassB
disp() method of ClassC

Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();

6
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

d.eat();
}}

Output:
weeping...
barking...
eating...

HIERARCHICAL INHERITANCE

In Hierarchical Inheritance, one class is inherited by many sub classes.


Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{

7
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

public static void main(String args[])


{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();
//Assigning ClassC object to ClassC
reference ClassC c = new ClassC();
//call dispC() method of ClassC
c.dispC();

//call dispA() method of ClassA


c.dispA();

//Assigning ClassD object to ClassD reference


ClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}
Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA

Example:

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{

8
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...

Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again
Hybrid inheritance is also not directly supported in Java only through interface we can
achieve this. Flow diagram of the Hybrid inheritance will look like below. As you can
ClassA will be acting as the Parent class for ClassB & ClassC and ClassB & ClassC will be
acting as Parent for ClassD.

Multiple Inheritance is nothing but one class extending more than one class. Multiple
Inheritance is basically not supported by many Object Oriented Programming languages such
as Java, Small Talk, C# etc.. (C++ Supports Multiple Inheritance). As the Child class has
to manage the dependency of more than one Parent class. But you can achieve multiple
inheritance in Java using Interfaces.

Java does not support multiple inheritance, which means a class cannot inherit
characteristics (methods and fields) from more than one superclass. The main reason
behind this is to avoid confusion and complexity caused by the "Diamond Problem".
Consider a real-life example where a child can have traits from both parents, but if
there's a conflict, such as eye color from the mother is brown and from the father is
blue, it's unclear which color the child should inherit.

9
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

Similarly, in Java, if class B and C inherit from A, and both override the same method
from A, then if a class D inherits from both B and C, it's unclear which method D
should inherit, hence creating a "diamond" shaped inheritance diagram. To avoid such
complications, Java prohibits multiple inheritance.

Key points related to inheritance:


 Inheritance helps in code reusability.
 Inheritance represents the IS-A relationship between classes.
 The keyword extends is used to perform inheritance.
 Multiple inheritance and Hybrid inheritance are not valid in Java, although
they can be performed on interfaces.
 super keyword can be used to access the variables/methods/constructor of the
parent class.

2.2 CONSTRUCTORS AND INHERITANCE

A constructor in Java is similar to a method with a few differences. Constructor has the
same name as the class name. A constructor doesn't have a return type.

A Java program will automatically create a constructor if it is not already defined in the
program. It is executed when an instance of the class is created.

A constructor cannot be static, abstract, final or synchronized. It cannot be overridden.

Java has two types of constructors:

1. Default constructor
2. Parameterized constructor

10
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

While implementing inheritance in a Java program, every class has its own constructor.
Therefore the execution of the constructors starts after the object initialization. It follows
a certain sequence according to the class hierarchy. There can be different orders of
execution depending on the type of inheritance.

1. Order of execution of constructor in Single inheritance

In single level inheritance, the constructor of the base class is executed first.

OrderofExecution1.java

/* Parent Class */
class ParentClass
{
/* Constructor */
ParentClass()
{
System.out.println("ParentClass constructor executed.");
}
}

/* Child Class */
class ChildClass extends ParentClass
{
/* Constructor */
ChildClass()
{
System.out.println("ChildClass constructor executed.");
}
}

public class OrderofExecution1


{
/* Driver Code */
public static void main(String ar[])
{

11
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

/* Create instance of ChildClass */


System.out.println("Order of constructor execution...");
new ChildClass();
}
}

Output:

Order of constructor execution...


ParentClass constructor executed.
ChildClass constructor executed.

In the above code, after creating an instance of ChildClass the ParentClass constructor is
invoked first and then the ChildClass.

2. Order of execution of constructor in Multilevel inheritance

In multilevel inheritance, all the upper class constructors are executed when an instance
of bottom most child class is created.

OrderofExecution2.java

class College
{
/* Constructor */
College()
{
System.out.println("College constructor executed");
}
}

class Department extends College


{
/* Constructor */
Department()
{
System.out.println("Department constructor executed");
}

12
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

class Student extends Department


{
/* Constructor */
Student()
{
System.out.println("Student constructor executed");
}
}
public class OrderofExecution2
{
/* Driver Code */
public static void main(String ar[])
{
/* Create instance of Student class */
System.out.println("Order of constructor execution in Multilevel inheritance...");
new Student();
}
}

Output:

Order of constructor execution in Multilevel inheritance...


College constructor executed
Department constructor executed
Student constructor executed

In the above code, an instance of Student class is created and it invokes the constructors
of College, Department and Student accordingly.

3. Calling same class constructor using this keyword

Here, inheritance is not implemented. But there can be multiple constructors of a single
class and those constructors can be accessed using this keyword.

13
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

OrderofExecution3.java

public class OrderofExecution3


{
/* Default constructor */
OrderofExecution3()
{
this("CallParam");
System.out.println("Default constructor executed.");
}
/* Parameterized constructor */
OrderofExecution3(String str)
{
System.out.println("Parameterized constructor executed.");
}
/* Driver Code */
public static void main(String ar[])
{
/* Create instance of the class */
System.out.println("Order of constructor execution...");
OrderofExecution3 obj = new OrderofExecution3();
}
}

Output:

Order of constructor execution...


Parameterized constructor executed.
Default constructor executed.

In the above code, the parameterized constructor is called first even when the default
constructor is called while object creation. It happens because this keyword is used as the
first line of the default constructor.

4. Calling superclass constructor using super keyword

A child class constructor or method can access the base class constructor or method using
the super keyword.

14
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

OrderofExecution4.java

/* Parent Class */
class ParentClass
{
int a;
ParentClass(int x)
{
a = x;
}
}

/* Child Class */
class ChildClass extends ParentClass
{
int b;
ChildClass(int x, int y)
{
/* Accessing ParentClass Constructor */
super(x);
b = y;
}
/* Method to show value of a and b */
void Show()
{
System.out.println("Value of a : "+a+"\nValue of b : "+b);
}
}

public class OrderofExecution4


{
/* Driver Code */
public static void main(String ar[])
{
System.out.println("Order of constructor execution...");
15
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

ChildClass d = new ChildClass(79, 89);


d.Show();
}
}

Output:

Order of constructor execution...


Value of a : 79
Value of b : 89

In the above code, the ChildClass calls the ParentClass constructor using
a super keyword that determines the order of execution of constructors.

2.3 SUPER KEYWORD

The super keyword in Java is a reference variable which is used to refer immediate parent
class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";

16
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}

Output:

black
white

In the above example, Animal and Dog both classes have a common property color. If we
print color property, it will print the color of current class by default. To access the parent
property, we need to use super keyword

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{

17
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

public static void main(String args[]){


Dog d=new Dog();
d.work();
}}

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat()
method from Dog class, it will call the eat() method of Dog class by default because
priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created

18
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

Note: super() is added in each class constructor automatically by compiler if there


is no super() or this().

As we know well that default constructor is provided by compiler automatically if there


is no constructor. But, it also adds super() as the first statement.

Another example of super keyword where super() is provided by the compiler


implicitly.

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created

19
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

super example: real use

Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property, we
are using parent class constructor from child class. In such way, we are reusing the parent
class constructor.

class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}

Output:

1 ankit 45000

20
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

2.4 METHOD OVERRIDING

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

 Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.
 Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method
overriding.

Example //Java Program to demonstrate why we need method overriding


//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance

21
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

obj.run();
}
}

Output:
Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass


that is why we use method overriding.

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent
class but it has some specific implementation. The name and parameter of the method
are the same, and there is IS-A relationship between the classes, so there is method
overriding.

Example //Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Output:

Bike is running safely

22
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

A real example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI, ICICI
and AXIS banks could provide 8%, 7%, and 9% rate of interest.

Example //Java Program to demonstrate the real scenario of Java Method Overriding

//where three classes are overriding the method of a parent class.

//Creating a parent class.


class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{

23
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

public static void main(String args[]){


SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

2.5 DYNAMIC METHOD DISPATCH

Polymorphism in Java is a concept by which we can perform a single action in different


ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and
method overriding.

If you overload a static method in Java, it is the example of compile time polymorphism.

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an


overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a


superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:

24
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

class A{}
class B extends A{}
A a=new B();//upcasting

For upcasting, we can use the reference variable of class type or an interface type. For
Example:

interface I{}
class A{}
class B extends A implements I{}

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A Object.

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendor. Splendor class extends
Bike class and overrides its run() method. We are calling the run method by the reference
variable of Parent class. Since it refers to the subclass object and subclass method
overrides the Parent class method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.

25
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
}

Output:

running safely with 60km.

Java Runtime Polymorphism Example: Bank

Consider a scenario where Bank is a class that provides a method to get the rate of
interest. However, the rate of interest may differ according to banks. For example, SBI,
ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.

class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{

26
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

float getRateOfInterest(){return 8.4f;}


}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

Output:

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Java Runtime Polymorphism Example: Shape

class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}

27
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

class Circle extends Shape{


void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}

Output:

drawing rectangle...
drawing circle...
drawing triangle...

2.6 ABSTRACT CLASSES AND METHODS

A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know
the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

28
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

ABSTRACT CLASS IN JAVA

A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It cannot
be instantiated.

Points to Remember
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of
the method.

Example of abstract class

abstract class A{}

ABSTRACT METHOD IN JAVA

A method which is declared as abstract and does not have implementation is known as
an abstract method.

Example of abstract method

abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
29
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Output:
running safely

If there is an abstract method in a class, that class must be abstract.

class Bike12{
abstract void run();
}

Output:
compile time error
Rule: If you are extending an abstract class that has an abstract method, you must either
provide the implementation of the method or make this class abstract.

2.7 FINAL KEYWORD

The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:

1. variable
2. method
3. class

30
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

The final keyword can be applied with the variables, a final variable that have no value
it is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.

1) Java final variable

If you make any variable as final, you cannot change the value of final variable (It will
be constant).

Example of final variable

There is a final variable speed limit, we are going to change the value of this variable,
but It can't be changed because final variable once assigned a value can never be
changed.

class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}//end of class
Output:
Compile Time Error

2) Java final method

If you make any method as final, you cannot override it.

Example of final method

class Bike{
final void run(){System.out.println("running");}
}

31
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Output:
Compile Time Error

3) Java final class

If you make any class as final, you cannot extend it.

Example of final class

final class Bike{}

class Honda1 extends Bike{


void run()
{System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output:
Compile Time Error

32
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

2.8 INTERFACES

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction;


means all the methods in an interface are declared with the empty body, and all the fields
are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

33
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

Syntax:

interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods
are public and abstract.

The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

34
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

2.9. IMPLEMENTING AN INTERFACE

Example Interface

In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
} }

Output:

Hello

Example:Interface Drawable

In this example, the Drawable interface has only one method. Its implementation is
provided by Rectangle and Circle classes. In a real scenario, an interface is defined by
someone else, but its implementation is provided by different implementation providers.
Moreover, it is used by someone else. The implementation part is hidden by the user who
uses the interface.

File: TestInterface1.java

//Interface declaration: by first user


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}

35
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDr
awable()
d.draw();
}}
Output:
drawing circle

Example: Interface Bank

Let's see another example of java interface which provides the implementation of Bank
interface.

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}

Output:

ROI: 9.15

36
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

2.10 MULTIPLE INHERITANCE THROUGH INTERFACE

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is


known as multiple inheritance.

Example

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
} }
Output:
Hello
Welcome

37
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstract methods. 8, it can have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.

6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves
fully abstraction (100%).

38
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

Example of abstract class and interface in Java

Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods


interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}
//Creating abstract class that provides the implementation of one method of A inter
face
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
//Creating subclass of abstract class, now we need to provide the implementation o
f rest of the methods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}

//Creating a test class that calls the methods of A interface


class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}

39
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS

Output:

I am a
I am b
I am c
I am d

40

You might also like