You are on page 1of 37

Inheritance & Interfaces

BY: Prof. Pavan Malani


 A mechanism of deriving a new class from an existing class is known as
inheritance. The old class is known as base class whereas new class is
known as derived class.
 The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes
 Inheritance refers the property of class being available to many other
subclasses. It incorporates all the features of base class that can inherit in
the derive class.
 Derive class has got more properties as compare to base class
because it has its own property and also access the properties of base class
 To inherit a class in java we simply use keyword extends.
 .
 Terms used in Inheritance
 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.
ADVANTAGES OF INHERITANCE
1.Reusability:
i)Once the class is defined it can be reused to create a new
subclasses, so rewriting of same code becomes unnecessary.
ii)Data methods of superclass are physically available to all of its
subclasses.
iii)In inheritance we use keyword protected through which we can
access the properties of base class immediately in the derived class.
 Types of inheritance in java
 On the basis of class, there can be three types of inheritance in
java: single, multilevel and hierarchical.
 In java programming, multiple and hybrid inheritance is supported
through interface only.
Single Inheritance Example: When a class inherits another class, it is known as a single inheritance. In the
example given below, 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 TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
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 TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
WAP create a class student with roll no & name . Derive a class subject which consists
of marks of 3 subjects. Write a function to accept & display the details of student &
also calculate total & percentage . Accept all input from command line argument.
class stud
{
int rno;
String name;
void accept(int r, String n)
{
rno=r;
name=n;
}
void disp()
{
System.out.println(rno+ " "+name);
}
}
class subject extends stud
{
int m1,m2,m3;
void get(int x, int y, int z)
{
m1=x;
m2=y;
m3=z;
}
void show()
{
System.out.println("Marks of 3 subjects" +m1 +" "+m2+" "+m3);
}

void cal()
{
int tot=m1+m2+m3;
float per=(float) tot/3;
System.out.println (tot+ " "+per);
}}
class prog1
{
public static void main(String args[])
{
subject t= new subject();
int r= Integer.parseInt(args[0]);
String name=args[1];
int m1=Integer.parseInt(args[2]);
int m2=Integer.parseInt(args[3]);
int m3=Integer.parseInt(args[4]);
t.accept(r,name);
t.disp();
t.get(m1,m2,m3);
t.show();
t.cal();
}}
WAP to illustrate multilevel inheritance such that country is inherited from continent, state is
inherited from country, place is inherited from state. Display place, country, state & continent.
class continent class state extends country
{ {

protected String cont protected String sname;


void accept1()
void get()
{
{
sname=“Maharashtra”; }
cont=“asia”;
class place extends state
}
{
class country extends continent
String pname;
{
void accept2()
protected String cname; {
void accept() pname=“Nashik”;
{ }
cname=“India”;
}
void show()
{
System.out.println(“Continent is” +cont);
System.out.println(“Country is” +cname);
System.out.println(“State name” +sname);
System.out.println(“Place is” +pname);
}}
class test22
{
public static void main(String args[])
{
place t=new place();
t.get();
t.accept();
t.accept1();
t.accept2();
t.show();
}}
METHOD OVERRIDING IN JAVA
Methods in the derive class can have similar name and similar
parameters as methods in base class such a methods are known as overrided
method
When we call methods in the derive class it hides the methods of base
class so in order to call methods in base class java provides “super” keyword
SUPER KEYWORD
Super keyword is used to access the methods, variables and constructors of
base class when they are overridden by derive class.
i)calling overrided method
When methods are overridden then in order to call methods of a base class
we write “super.method name()” in the derive class method.
ii)Calling overrided constructor
When both base and derive class contains a constructor then
in order to call or access base class constructor we write
“super()” as a first statement in the derive class constructor.
iii)Accessing overrided variable
When the variable names are same in both base & derive
class but values are different. Then to access base class
variable we write “super.variable name” in derive class
method.
Demo code of calling overrided methods using super keyword
class abc class inh11
{ {
void disp() public static void main(String args[])
{ {
System.out.println("this is abc class"); pqr t=new pqr();
} t.disp();
}
class pqr extends abc }
{
}
void disp()
{
super.disp();
System.out.println("this is pqr class");
}
}
Calling overrided method
class emp {
{ super.accept(e,n);
int eno; ano=ano1;
String ename; aname=nm;
void accept(int e, String n) asal=sal;
{ }
eno=e; void show()
ename=n; {
} super.show();
void show() System.out.println (“applicant no” +ano);
{ System.out.println (“name” +aname);
System.out.println(“employee no” +eno); System.out.println(“salary” +asal);
System.out.println(“employee name” +ename); }}
}} class test41
class applicant extends emp {
{ public static void main(String args[])
int ano,asal; {
String aname; applicant t=new applicant();
void accept(int e, String n, int ano1, int sal, String nm) t.accept(101, “abc”,11,20000, “pqr”);
t.show();
}}
Calling Overrided Constructor
class abc class super2
{ {
abc(int a,int b) public static void main(String args[])
{ {
System.out.println("the value of a & b is"+a+" "+b); pqr t=new pqr(10,20,30,40);
}
}
class pqr extends abc }
{
pqr(int a,int b,int x,int y) }
{
super(a,b);
System.out.println("the value of x & y is"+x+" "+y);
}

}
ABSTRACT METHODS AND CLASSES
Abstarct method
The methods which are only declared but not define is known as
abstract method
To declare abstract method keyword abstract is used.
Abstract Class
The class which contain abstract method is known as abstract class.
An abstract class provides all the required functionality which is used
by all its subclasses. It basically contains common characteristics all
derive class.
Characteristics of abstract class
i)An object of abstract class can not be created by using new keyword instead of
that we only create reference object of the abstract class.
ii)Abstract method can not be declare as a final.
Example
 Create an abstract class shape with method area & volume. Derive a class
cylinder & sphere which has a parameter radius & height. WAP to calculate
area & volume of above two shapes use abstract method and class.
abstract class shape
{
abstract void area(int r, int h);
abstract void volume(int r, int h);
}
class cylinder extends shape
{
void area(int r, int h)
{
float ans=2*3.14f*r*r*h;
System.out.println("area of cylinder" +ans);
}
void volume(int r, int h)
{
float ans1=3.14f*r*r*h;
System.out.println("volume of cylinder" +ans1);
}}
class sphere extends shape
{
void area(int r, int h)
{
float ans=4*3.14F*r*r;
System.out.println("area of sphere" +ans);
}
void volume(int r, int h)
{
float ans=(4/3)*3.14f*r*r*r;
System.out.println("volume of sphere is" +ans);
}}
class abstract1
{
public static void main(String args[])
{
shape t;
cylinder t1=new cylinder();
t=t1;
t.area(5,7);
t.volume(3,2);
sphere t2=new sphere();
t=t2;
t.area(3,8);
t.volume(2,7);
}}
Create an abstract class person with method accept & display. Derive two classes employee &
worker from it. Employee class contains employee no, name & address. Similar fields used for
worker class with extra attribute working hour. Calculate salary of worker if rate per hour is 500
rupees
abstract class person
{
abstract void accept();
abstract void disp();
}
class emp extends person
{
int eno;
String enm,eaddr;
void accept()
{
eno=1;
enm="abc";
eaddr="Nashik";
}
void disp()
{
System.out.println("emp no is:"+eno);
System.out.println("ename is:"+enm);
System.out.println("emp address is:"+eaddr);
}
}
 class worker extends person
{
int wno,whrs;
String wnm,waddr;
void accept()
{
wno=101;
wnm="pqr";
waddr="Pune";
whrs=10;
}
void disp()
{
int sal=whrs*500;
System.out.println("worker no is:"+wno);
System.out.println("wname is:"+wnm);
System.out.println("worker address is:"+waddr);
System.out.println("working hours:"+whrs);
System.out.println("total salary is"+sal);
}
}
 class abstract2
{
public static void main(String args[])
{
person t;
emp t1=new emp();
t=t1;
t.accept();
t.disp();
worker t2=new worker();
t=t2;
t.accept();
t.disp();
}
}
Interface
An interface is basically a kind of a class with major
difference is that the variables which are declared inside the
interface are by default public, static and final and the
methods which are declared inside the interface are by
default public and abstract
Java does not support multiple inheritance so in order to
support multiple inheritance we use the concept interface.
To declare interface keyword interface is used . When any
class is derived from interface then it is implements not
extends.
Create an interface shape. Define a class rectangle & circle from
it WAP to calculate area of circle & rectangle.
interface shape class test 37
{ {
public void area(); public static void main(String args[])
} {
class circle implements shape shape t;
{ circle t1=new circle();
int r=7 t=t1;
public void area() t.area();
{ rectangle t2=new rectangle();
float ans=3.14*r*r; t=t2;
System.out.println(“area of circle is” +ans); t.area();
}} }}
class rectangle implements shapes
{
int l=5, b=7;
public void area()
{
int ans= l*b;
System.out.println(“area of rectangle” +ans);
}}
WAP which create interface conversion with method gm to kg & kg to gm. Write this
function to convert value gm to kg & vice versa Accept input through command line
argument
interface conversion class test39
{ {
int var=1000; public static void main(String args[])
public void gmtokg(int gm); {
public void kgtogm(int kg); int gm=Integer.parseInt(args[0]);
} int kg=Integer.parseInt(args[1]);
class convert implements conversion conversion t;
{ convert t1=new convert();
public void gmtokg(int gm) t=t1;
{ t.gmtokg(gm);
float ans=gm/var; t.kgtogm(kg);
System.out.println(“gm to kg=” +ans); }
} }
public void kgtogm(int kg)
{
float ans1=kg*var;
System.out.println(“kg to gm=” +ans1);
}}
TYPES OF INTERFACE
There are two types of interface
i)Partial interface
ii)Extended interface
i)Partial implementation of interface
If class implements an interface but does not implement all
the method declare by that interface then it is known as Partial
implementation of interface.
eg interface conversion class test42
{ {
int var=100; public static void main(String args[])
public void gmtokg(int gm); {
public void kgtogm(int kg); conversion s;
} convertsub t=new convertsub();
Abstract class convert implements conversion s=t;
{ s.gmtokg(5000);
public void gmtokg(int gm) s.kgtogm(3);
{ }
float ans=gm/var; }
System.out.println(“gm to kg=” +ans);
}}
class convertsub extends convert implements conversion
{
public void kgtogm(int kg)
{
float ans=kg*var;
System.out.println(“kg to gm=” +ans);
}}
ii)Extended interface
We can inherit one interface from another interface by using
keyword extends . Here all the methods of base interface
will be accessible in derive interface
Ex. WAP to create an interface employee which contains
variable emp name, id & city. Derive an interface emp
show which display all the details of emp. Implement
above both interface in class & display the details
.
interface emp class test43
{ {
int eid=101; public static void main(String args[])
String ename=“abc”; {
String ecity=“nashik”; empshow t;
} empinfo t1=new empinfo();
interface empshow extends emp t=t1;
{ t.disp();
public void disp(); }
} }
class empinfo implements empshow
{
void disp()
{
System.out.println(eid+” “+ename+” “+ecity);
}
}
IMPLEMENTING MULTIPLE INHERITANCE IN JAVA
As java does not support multiple inheritance like c++ we require several
base classes and one derive class
To overcome this we use interface concept as follows

student subject

class student
{
result
}
interface subject
{
}
class result extends student implements subject
{
}
Create a class student with attribute rno. Derive a class test from class student which
contain marks of two subject. Create an interface sports which contain marks of sports
subject. Derive class result from class test & interface sports which calculates total &
percentage of above marks and display the details
 class student  class test extends student
{ {
int rno; protected int m1,m2;
void get(int r) void getmarks(int a,int b)
{ {
rno=r; m1=a;
} m2=b;
void print() }
{ void disp()
System.out.println("roll no"+rno); {
} System.out.println(m1+""+m2);
} }
}
 interface sports  class intcal
{ {
int smarks=30; public static void main(String args[])
void show(); {
void cal(); sports t;
} result r=new result();
r.get(10);
r.print();
 class result extends test implements sports
r.getmarks(25,28);
{
r.disp();
public void show()
t=r;
{
t.show();
System.out.println("sports marks:"+smarks);
t.cal();
}
}
public void cal()
}
{
int tot=m1+m2+smarks;
System.out.println("total :"+tot);
}
}
Define a class MyNumber having one private integer data member. Write a default
constructor to initialize it to 0 and another constructor to initialize it to a value (Use
this). Write methods isNegative, isPositive, isZero, isOdd, isEven. Create an object in
main. Use command line arguments to pass a value to the object and perform the above
tests.(slip 18)
MyNo(int a)
interface IntOperations
{ {
void isPositive(); this.a=a;
void isNegative(); }
void iseven();
public void isPositive()
void isOdd();
void isZero(); {
} if(a>0)
class MyNo implements IntOperations System.out.println("The no is
{ Positive");
private int a;
}
MyNo()
{
a=0;
}
public void isNegative() }
{
if(a<0)
System.out.println("The no is Nigative");
}
public void iseven()
{
if(a%2==0)
System.out.println("The no is even");
}
public void isOdd()
{
if(a%2!=0)
System.out.println("The no is Odd");
}
public void isZero()
{
if(a==0)
System.out.println("The No is Zero ");
else
System.out.println("The no is not zero");
}
public static void main(String args[])
{
int a1=Integer.parseInt(args[0]);
MyNo m=new MyNo();
MyNo m1=new MyNo(a1);
IntOperations i;
i=m1;
i.isPositive();
i.isNegative();
i.iseven();
i.isOdd();
i.isZero();
}

You might also like