0% found this document useful (0 votes)
4 views

unit 3

Uploaded by

nish6557
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

unit 3

Uploaded by

nish6557
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

SE Semester-III

Object Oriented Programming with Java


Unit-3
Inheritance and Interfaces

Subject Teacher : Dr. K. V. Metre

https://beginnersbook.com/2013/03/inheritance-in-java/

https://www.geeksforgeeks.org/inheritance-in-java/
www.javatpoint.com/

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 1


Inheritance

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 2
University
Inheritance
• Inheritance is a mechanism in which one object acquires all the
properties and behaviors of a parent object.

• It is an important part of OOPs (Object Oriented programming


system).

• You can create new classes that are built upon existing classes.
• When you inherit from an existing class, you can reuse methods
and fields of the parent class.

• you can add new methods and fields in your current class also.
• Inheritance represents the IS-A relationship which is also known
as a parent-child relationship.
• For Code Reusability.
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 3
• Inheritance is a process of defining a new class based on
an existing class by extending its common data members
and methods.
• Inheritance allows us to reuse of code, it improves
reusability in your java application.
• The biggest advantage of Inheritance is that the code
that is already present in base class need not be
rewritten in the child class.
• This means that the data members(instance variables)
and methods of the parent class can be used in the child
class as.
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 4
Terms used in Inheritance
• 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, sub 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 the previous class.

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 5


The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
• The extends keyword indicates that you are making a new
class that derives from an existing class. The meaning of
"extends" is to increase the functionality.
• In the terminology of Java, a class which is inherited is
called a parent or superclass, and the new class is called
child or subclass.

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 6


class Superclass_name { ..... ..... }

class derived_class_name extends Superclass-name


{
// body of the derived class.
}
Class Person {
protected String name;
protected int mob;
protected String address;
}
Class Student extends Person
{
float per;
String branch;
int year;
}
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 7
class Employee{
protected float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);


Programmer is the subclass
Employee is the superclass. System.out.println("Bonus of Programmer is:"+p.bonus);

The relationship between }


the two classes is }

Programmer IS-A Output :


Employee.
Programmer salary is:40000.0
It means that Programmer Bonus of programmer is:10000
is a9/28/2024
type of Employee. Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 8
Types of inheritance
• On the basis of class, there can be different types of
inheritance
1) Single ( Java & C++)
2) Multilevel ( Java & C++)
3) Hierarchical. ( Java & C++)
4) Multiple (C++)
5) Hybrid ( C++)
• In Java programming, multiple and hybrid inheritance is
supported through interface only.

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 9


9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 10
Single Inheritance Example
• When a class inherits another class, it is known as a single inheritance.
• Dog class inherits the Animal class, so there is the single inheritance.
-------------------------
class Animal{
void eat(){ System.out.println("eating..."); }
}
class Dog extends Animal{
void bark(){ System.out.println("barking..."); }
}
class Test{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating..
Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 11
University
Method Overriding/Polymorphism
• If subclass (child class) has the same method as declared in the
super class, it is known as method overriding in Java.

• Method signature should be same in super class and sub class.

• 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

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 12


9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 13
Method Overriding
class Vehicle{
public void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){

Bike obj = new Bike(); //creating an instance of child class

obj.run(); //calling the method with child class instance


} // here method overriding is not done
}
Output :
Vehicle is running

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 14


//Java Program to illustrate the use of Java Method Overriding
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");} }

//Creating a child class


class Bike extends Vehicle{
//defining the same method as in the parent class ,method
overriding
void run(){System.out.println("Bike is running ");}

public static void main(String args[]){


Bike obj = new Bike();
obj.run();// here method overriding is done }
}
Output :
Bike is running Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 15
University
Without method overriding
public void show()
class Person { {
protected String name; System.out.println("Name: " + name + "
Mobile No : " + mob);
protected int mob; System.out.println("Branch: " + branch + " Year :
public void getdata( String n, int m) " + year);
}
{
name = n; }
mob = m; } public class Main {
public void show() public static void main(String [] args)
{
{ Person p1 = new Person();
System.out.println("Name: " + name + " Mobile
No : " + mob); p1.getdata("AAAA", 11111111);
} System.out.println("Person Details \n");
p1.show();
}
class Student extends Person Student s1 = new Student();
{ s1.getdata("BBBBB", 222222, "IT", 2);
String branch; System.out.println("\n Student Details \n");
s1.show();
int year;
public void getdata( String n, int m, String b, int y) }
{ }
name = n;
mob = m; Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 16
branch = b; year = y; } University
With method overriding public void show()
class Person { {
protected String name; super.show();
protected int mob; System.out.println("Branch: " + branch + "
public void getdata( String n, int m) Year : " + year);
} }
{
public class Main {
name = n;
public static void main(String [] args)
mob = m; } {
public void show() Person p1 = new Person();
{
System.out.println("Name: " + name + " Mobile p1.getdata("AAAA", 11111111);
No : " + mob); System.out.println("Person Details \n");
} p1.show();
}
Student s1 = new Student();
class Student extends Person
s1.getdata("BBBBB", 222222, "IT", 2);
{
System.out.println("\n Student Details \n");
String branch; s1.show();
int year;
public void getdata( String n, int m, String b, int y) }}
{
super.getdata(n, m);
Here getdata() and show() methods are
overridden. Super keyword is used
branch = b; year = y; } nto call method of super class
Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 17
University
• Output :
Person Details

Name: AAAA Mobile No : 11111111


Student Details

Name: BBBBB Mobile No : 222222


Branch: IT Year : 2

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 18
University
Multilevel Inheritance Example
• When there is a chain of inheritance, it is known as multilevel inheritance. As
you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.
-------------------------
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 Test{
public static void main(String args[]){
Dog d1=new Dog();
d1.eat(); d1.bark(); //d1.weep(); //error

BabyDog d=new BabyDog();


d.eat(); d.bark(); d.weep(); }
9/28/2024 19
} Dr. K. V. Metre, SOCSET, ITM SLS Baroda University
• Hierarchical Inheritance Example
• When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

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

void sound(){ System.out.println("barking"); }


}
class Cat extends Animal{
void sound(){ System.out.println("meowing"); }
}
class Test{
public static void main(String args[]){
Cat c=new Cat();
c.sound();
c.eat();
Dog d=new Dog(); d.sound();
}}
Output:
meowing
eating
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 20
class Super{
public void msgsuper() { System.out.println("Executing Superclass"); }
}
class Sub1 extends Super {
public void msgsub1() { System.out.println("Executing Subclass one"); }
}
class Sub2 extends Super {
public void msgsub2() { System.out.println("Executing Subclass two"); }}
Public class Main{
public static void main(String[] args) {
Sub1 c = new Sub1();
c.msgsuper();
c.msgsub1();
System.out.println();
Sub2 j = new Sub2 ();
j.msgsuper()
j.msgsub2();
}}
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 21
• Visibility modifiers determine which class members are
inherited and which are not
• Variables and methods declared with public visibility are
inherited; those with private visibility are not inherited.
• But public variables violate the principle of encapsulation
• There is a third visibility modifier that helps in inheritance
situations: protected.
• The protected modifier allows a member of a base class to be
inherited into a child
• Protected visibility provides more encapsulation than public
visibility does
• However, protected visibility is not as tightly encapsulated as
private visibility

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 22
University
Access Specifiers
/* private members remain private to their class. This program will not compile. */
class A {
int i;
private int j;
void setij(int x, int y) {
i = x; j = y;
}}
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String args[]) { Access.java:10: error: j has
B b = new B(); private access in A
b.setij(10, 12); total = i + j; // ERROR, j is
b.sum(); not accessible here
System.out.println("Total is " + b.total);
}}
Output :
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 23
class Person { Access Specifiers
public class Main {
private String class Student extends
public static void
name; Person main(String [] args)
protected int { String branch; {
int year; Person p1 = new Person();
mob;
public void getdata( p1.getdata("AAAA",
public void
String n, int m, String 11111111);
getdata( String n, b, int y) {
int m) super.getdata(n, m);
System.out.println("Person
Details \n");
{ name = n; branch = b; year = y; } p1.show();
mob = m; } public void show(){
Student s1 = new
public void show() super.show(); Student();
{ System.out.println("Branc s1.getdata("BBBBB",
h: " + branch + " Year 222222, "IT", 2);
System.out.printl System.out.println("\n
: " + year);
n("Name: " + Student Details \n");
} s1.show();
name + "
}
Mobile No : " + }
mob); }} } 24
class BoxWeight extends Box {
Multilevel Inheritance double weight; // weight of box
Class Rect { BoxWeight(double w, double h, double d, double m)
{
Protected int len; super(w,h,d);
Protected int breadth; weight = m; } }
Void show()
public Rect(){ { super.show();}}
len=breadth=0; } class DemoBoxWeight {
public static void main(String args[]) {
public Rect(int l, int b){ BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
len=l; BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
breadth=b;} vol = mybox1.volume();
Public void show(){ System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " +
System.out.println(“Length=“+len+” ybox1.weight);
Breadth=“ +breadth);} } System.out.println();
vol = mybox2.volume();
class Box extends Rect { System.out.println("Volume of mybox2 is " + vol);
double depth; System.out.println("Weight of mybox2 is " +
mybox2.weight);
// construct clone of an object }}
public Box() { Output :
Volume of mybox1 is 3000.0
super(); Weight of mybox1 is 34.3
depth=0;} Volume of mybox2 is 24.0
9/28/2024 25
Weight of mybox2 is 0.076
A Superclass Variable Can Refer a Subclass Object
A reference variable of a superclass can be assigned a reference
to any subclass derived from that superclass.
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println(); // assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox does not define a weight
member. */
// System.out.println("Weight of plainbox is " + plainbox.weight); } }
Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 26
University
Using super
• This usage has the following general form:
super.member
• member can be either a method or an instance
variable.
• This 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

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 27
University
class Super
{ int value = 111;
}
class Sub1 extends Super{
int value = 222;
public void print()
{ System.out.println("From superclass:" + super.value);
System.out.println("From subclass:" + value);
}}
public class Main{
public static void main(String s[])
{ System.out.println("Using super:");
Sub1 ob = new Sub1();
ob.print();
} }
Output : Using super:
From superclass:111
Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 28
From subclass:222 University
Using super keyword
• Constructors are not inherited, even though they have public
visibility
• Yet we often want to use the parent's constructor to set up the
"parent's part" of the object
• The super reference can be used to refer to the parent class, and
often is used to invoke the parent's constructor.
• A child’s constructor is responsible for calling the parent’s
constructor
• The first line of a child’s constructor should use the super
reference to call the parent’s constructor
• The super reference can also be used to reference other variables
and methods defined in the parent’s class

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 29
University
Constructor using Super
• Using super 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.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 30
University
Without using super keyword class BoxWeight extends Box {
class Box { double weight; // weight of box
double width; BoxWeight(double w, double h, double d, double m)
double height; {
double depth; width = w; height = h; depth = d; weight = m; } }
// construct clone of an object class DemoBoxWeight {
Box(Box ob) { // pass object to constructor public static void main(String args[]) { BoxWeight
width = ob.width; mybox1 = new BoxWeight(10, 20, 15, 34.3);
height = ob.height; BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
depth = ob.depth; } double vol;
Box(double w, double h, double d) { vol = mybox1.volume(); System.out.println("Volume
width = w; of mybox1 is " + vol);
height = h; System.out.println("Weight of mybox1 is " +
mybox1.weight);
depth = d; }
System.out.println();
Box() {
vol = mybox2.volume(); System.out.println("Volume
width = height = depth = 10;} of mybox2 is " + vol);
Box(double len) { System.out.println("Weight of mybox2 is " +
width = height = depth = len; } mybox2.weight);
volume double volume() { }}
return width * height * depth; } Output :
} Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
9/28/2024
Dr. K. V. Metre, SOCSET, ITM SLS Weight of mybox2 is 0.076 31
Baroda University
class BoxWeight extends Box {
using super keyword double weight; // weight of box
class Box {
double width; BoxWeight(BoxWeight ob) { // pass object to constructor
double height; super(ob);
double depth; weight = ob.weight; } // are specified
// construct clone of an object BoxWeight(double w, double h, double d, double m) {
Box(Box ob) { // pass object to constructor super(w, h, d); // call superclass constructor
width = ob.width; weight = m; } // default constructor
height = ob.height; BoxWeight() {
depth = ob.depth; } super();
Box(double w, double h, double d) { weight = -1; }
width = w; // constructor used when cube is created
height = h; BoxWeight(double len, double m) {
depth = d; } super(len);
Box() { weight = m; }
width = height = depth = 10;} }
Box(double len) { class DemoBoxWeight {
width = height = depth = len; } public static void main(String args[]) {
volume double volume() { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
return width * height * depth; } BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
} double vol;
vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol)
System.out.println("Weight of mybox2 is " + mybox2.weight);
}}
Output :
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
Dr. K. V. Metre, SOCSET, ITM SLS
9/28/2024 32
Baroda University
class DemoSuper {
System.out.println();
public static void main(String args[]) {
vol = myclone.volume();
BoxWeight mybox1 = new BoxWeight(10, 20,
System.out.println("Volume of myclone is
15, 34.3);
" + vol);
BoxWeight mybox2 = new BoxWeight(2, 3, 4,
0.076); System.out.println("Weight of myclone is " +
myclone.weight);
BoxWeight mybox3 = new BoxWeight();
BoxWeight myclone = new System.out.println();
BoxWeight(mybox1); vol = mycube.volume();
double vol; System.out.println("Volume of mycube is "
vol = mybox1.volume(); + vol);
System.out.println("Volume of mybox1 is " System.out.println("Weight of mycube is " +
+ vol); mycube.weight);
System.out.println("Weight of mybox1 is " + System.out.println(); } }
mybox1.weight); System.out.println(); output:
vol = mybox2.volume(); Volume of mybox1 is 3000.0
System.out.println("Volume of mybox2 is " Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
+ vol);
Weight of mybox2 is 0.076
System.out.println("Weight of mybox2 is " + Volume of mybox3 is -1.0
mybox2.weight); Weight of mybox3 is -1.0
Volume of myclone is 3000.0
System.out.println(); vol = mybox3.volume();
Weight of myclone is 34.3
System.out.println("Volume of mybox3 is " Volume of mycube is 27.0
+ vol); System.out.println("Weight of Dr. K. V. Metre, SOCSET,
Weight ITM
of mycube is 2.0University
SLS Baroda 33
mybox3 is " + mybox3.weight);
Method overriding
• A child class can override the definition of an inherited method in favor
of its own
• The new method must have the same signature as the parent's method,
but can have a different body
• The type of the object executing the method determines which version
of the method is invoked
• A parent method can be invoked explicitly using the super reference
• If a method is declared with the final modifier, it cannot be
overridden
• The concept of overriding can be applied to data and is called
shadowing variables
• Shadowing variables should be avoided because it tends to cause
unnecessarily confusing code

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 34
University
Method Overloading vs. Overriding
• Overloading deals with multiple methods with the same
name in the same class, but with different signatures

• Overriding deals with two methods, one in a parent


class and one in a child class, that have the same name

• Overloading lets you define a similar operation in


different ways for different data

• Overriding lets you define a similar operation in


different ways for different object types

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 35
University
• In a class hierarchy, 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.

• When an overridden method is called from within a


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.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 36
University
class A { class Override {
public static void main(String args[]) {
int i, j; B b1 = new B(1, 2, 3);
A(int a, int b) {
b1.show();
i = a; j = b; } // display i and j // this calls show() in B
void show() { }
System.out.println("i and j: " + i + " " }
+ j); } } Output
class B extends A { k: 3
int k;
B(int a, int b, int c) {
super(a, b);
k = c; }
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k); }
}
Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 37
University
final keyword
• Final keyword can be used for instance variable,
method and class.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 38
University
final variable Example
class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; // } It can't be changed because final variable

once assigned a value can never be changed.

public static void main(String args[]){


Bike obj=new Bike();
obj.run();
}
}//end of class
Test it Now
Output:
Compile Time Error
Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 39
University
Java final method
• If you make any method as final, you cannot override it
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");
} // can not override final method

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
} }
Output:
Compile Time Error
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 40
Java final class
• If you make any class as final, you cannot extend it.

final class Bike{ }


class Honda extends Bike{
void run(){
System.out.println("running with 100kmph");}

public static void main(String args[]){


Honda h1= new Honda();
h1.run();
}
}
Output:
Compile Time Error
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 41
Stop inheritance
Stopping Inheritance with Final Keyword

•Definition:
•When a class is declared as final, it cannot be subclassed
/inherited
Example:

final class FinalClass { }

Class A extends FinalClass {


} // not possible

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 42
University
Interface in Java

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 43
University
Interface
• 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.

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 44


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.

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 45


• 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.
• Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
e.g.
interface Animal {
void sound();
}
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 46
The relationship between classes and interfaces

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 47
University
interface printable{
void print();
}
class A implements printable{ //method overriding
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A obj = new A();
obj.print();
}
}
Output:
Hello
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 48
Drawable interface has only one method. Its implementation is provided by Rectangle
and Circle classes.
interface Drawable{
void draw(); }
class Rectangle implements Drawable{
public void draw(){
System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){ System.out.println("drawing circle");} }
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
Drawable d=new Rectangle();// object is provided by method e.g. getDrawable()
d.draw(); }}
Output: drawing circle
drawing rectangle
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 49
Implementing class from 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 TestInterface{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
Bank b=new PNB();
System.out.println("ROI: "+b.rateOfInterest());}
}

Output:
ROI: 9.15
ROI: 9.7

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 50
University
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 51


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

public static void main(String args[]){

A obj = new A();


obj.print();
obj.show();
}
}
Output:
Hello
Welcome
Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 52
University
Multiple inheritance is not supported through class in java, but it is possible by
an interface,
multiple inheritance is not supported in the case of class because of ambiguity.
However, it is supported in case of an interface because there is no ambiguity.
It is because its implementation is provided by the implementation class.
interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface implements Printable, Showable {


public void print(){
System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
} }
Output: Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 53
Hello University
Static Method in Interface
Since Java 8, we can have static method in interface.
interface Drawable{
void draw();
static int cube(int x){return x*x*x;} }
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3)); //can be called using
//interface only
}}
Output:
drawing rectangle
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 54
27
Polymorphism in Java
• 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.

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 55


Runtime polymorphism or Dynamic method dispatch
• 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.
Upcasting :
• If the reference variable of Parent class refers to the
object of Child class, it is known as upcasting.

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 56


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.

Dynamic dispatch method program on next slide

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


9/28/2024 57
University
interface Shape { public void area () {
void area (); System.out.println ("Area of a Rectangle is
double pi = 3.14; : " + l*b );
} }}
class Circle implements Shape { class InterfaceDemo {
public static void main (String args[])
double r;
{
Circle (double radius)
Circle ob1 = new Circle (10);
{r = radius; }
ob1.area (); //dynamic method dispatch
public void area () {
Rectangle ob2 = new Rectangle (10,10);
System.out.println ("Area of a
ob2.area (); //dynamic method dispatch
circle is : " + pi*r*r );
}}
}}
class Rectangle implements
Shape { Output :
double l,b; Area of a circle is : 314
Rectangle (double length, double Area of a Rectangle is : 100
breadth)
{ l =9/28/2024
length; b = breadth;. }Dr. K. V. Metre, SOCSET, ITM SLS Baroda 58
University
instanceof operator
• instanceof' operator is used to test whether an object is an
instance of a specified type (class or sub - class or interface).
• It returns true or false.

class Student{ }
class Test{
public static void main( String args[ ] )
{
// declaring an object 's' of the student class
student s = new student( ) ;
// checking whether s is an instance of the student class
Boolean str = s instanceof student;
// printing the string value
System.out.println( str ) ;
}
Output : true
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 59
• An object of subclass type is also a type of parent class.

class Teacher { }
public class Student extends Teacher
{
public static void main( String args[ ] )
{
// declaring the object of the class 'Student'
Student s = new Student( ) ;
// checking whether the object s is the instance of the parent class ' Teacher '

Boolean str = s instanceof Teacher ;


// printing the boolean value
System.out.println( str ) ;
}
}
Output:
true
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 60
Difference between Abstract class and interface
S.N Abstract class interface
1 Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods Since Java 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,
Interface has only static and final variables.
static and non-static variables.
4 Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5 The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface
6 An abstract class can extend another
An interface can extend another Java
Java class and implement multiple Java
interface only.
interfaces.
7 A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
Dr. K. V. Metre, SOCSET, ITM SLS Baroda
9/28/2024 61
University
Inheritance and Substitutability

• Idealization of inheritance:instance of "subclass" can substitute for

instance of parent In Java, substitutability by implementing interfaces as

well as subclass

• Abstract concept captured with two rules of thumb:

• is-a relation "A Car is-a Vehicle" sounds right Natural for Car to inherit

from mammal

• has-a relation"A car is-a(n) engine" sounds wrong Not natural to use

inheritance But "a car has-a(n) engine" sounds right

• Can use composition (aggregation)


9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 62
Benefits of Inheritance :
• Software Reusability (among projects)
• Increased Reliability (resulting from reuse and
sharing of well-tested code)
• Code Sharing (within a project)
• Consistency of Interface (among related objects)
• Software Components
• Rapid Prototyping (quickly assemble from pre-
existing components)
• Polymorphism and Frameworks (high-level
reusable components)
• Information Hiding
9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 63
Conclusion
• Importance of Inheritance and Interfaces in code
organization.

• Enhancements in code reusability and maintenance.

9/28/2024 Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 64

You might also like