Unit 2
Unit 2
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.
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
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
3
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS
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
7
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 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.
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.
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.
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.");
}
}
11
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS
Output:
In the above code, after creating an instance of ChildClass the ParentClass constructor is
invoked first and then the ChildClass.
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");
}
}
12
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS
Output:
In the above code, an instance of Student class is created and it invokes the constructors
of College, Department and Student accordingly.
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
Output:
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.
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);
}
}
Output:
In the above code, the ChildClass calls the ParentClass constructor using
a super keyword that determines the order of execution of constructors.
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.
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
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
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.
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
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
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
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.
Let's understand the problem that we may face in the program if we don't use method
overriding.
21
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS
obj.run();
}
}
Output:
Vehicle is running
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.
Output:
22
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS
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
23
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS
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.
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{}
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.
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");}
Output:
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
Output:
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
Output:
drawing rectangle...
drawing circle...
drawing triangle...
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
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
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.
A method which is declared as abstract and does not have implementation is known as
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
Output:
running safely
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.
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.
If you make any variable as final, you cannot change the value of final variable (It will
be constant).
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
class Bike{
final void run(){System.out.println("running");}
}
31
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS
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.
There are mainly three reasons to use interface. They are given below.
33
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS
Syntax:
interface <interface_name>{
In other words, Interface fields are public, static and final by default, and the methods
are public and abstract.
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
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");}
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
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
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
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");}
37
23AD1303 OBJECT ORIENTED PROGRAMMING PARADIGM PEC DEPT OF AI & DS
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.
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.
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
Let's see a simple example where we are using interface and abstract class both.
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