1. Inheritance:
It is the process ofcreating IS-A relation between classes. in inheritance functionality of a
class are extended by defining a new class which inherits the feature of the existing class
and add some new features of its own.
Inheritance is used for codereusability and run time polymorphism.
Note:
Constructorof super class cannot be inherited in subclass.
A subclass can either add behavior or behavior and attributes.
Inheritance is unidirectional i.e subclass only inherit the super class.
Types of inheritance:
The following types are supported in java:
2. The following types are not supported in java
Hybrid and multiple inheritance is not supported for the following
reasons
1. To remove the ambiguity.
2. To provide more maintainable and clear design.
Examples:
in this example only instance variable are inherited in the
derived class A12 from base class A11.
Class A11
{
int a,b;
}
Class A12 extends A11 // A12 inherit A11
{
int c;
Public void show(int x,int y)
{
a=x;
b=y;
3. }
public void sum()
{
c=a+b;
SOP(“after addition c=”+c);
}
}
Class Test
{
Public static void main(String arr[])
{
A12 a=new A12();
a.show(10,20);
a.sum();
}}
in this example both instance variable and method are inherited
in the derived class A12 from base class A11.
class A11
{
int a,b;
int c;
public void show( int x,int y)
{
a=x;
b=y;
4. }
}
class A12 extends A11
{
public void sum()
{
c=a+b;
System.out.println(c);
}
}
class A13
{
public static void main(String arr[])
{
A12 a=new A12();
a.show(10,20);
a.sum();
}
}
5. Define a class vehicle with private instance variable
passenger,fuelcapcity and fuel consumption per km. calculate
the total distance to be covered with in a method by multiplying
fuelcapcity and fuel consumption per km.
define a new subclass truck with instance variable total load
capacity in tons. Display all information using a class
Truckdemo by declaring the method for class truck.
class vechile
{
private int noofpassenger;
private int fuelcap;
private int fuelconskm;
void setP(int p)
{
noofpassenger=p;
}
void setF(int f)
{
fuelcap=f;
}
void setFc(int fc)
{
fuelconskm=fc;
}
int getP()
{
6. return noofpassenger;
}
int getF()
{
return fuelcap;
}
int getFc()
{
return fuelconskm;
}
int td()
{
return fuelcap*fuelconskm;
}
}
class Truck extends vechile
{
int totalload;
public void display()
{
System.out.println("total load in truck="+totalload);
}
}
class TruckDemo
{
public static void main(String arr[])
{
Truck t1=new Truck();