2. Inheritance
• Different kinds of objects often have a certain amount of
properties in common with each other.
• For Example:
1. Mountain Bike
2. Road Bike
3. Tandems
• All share the characteristics of bicycles (speed, pedal,
gear).
• Yet each also defines additional features that make them
different: tandem bicycles have two seats and two sets of
handlebars; road bikes have drop handlebars; some
mountain bikes have an additional chain ring
4. Inheritance
• Inheritance allows the creation of hierarchal
classifications.
• Using inheritance, you can create a general class that
defines traits/features common to a set of related items.
• This class can then be inherited by other classes that add
other things that are unique to them.
• The class that is inherited is called “super class”
• The class that does the inheriting is called “sub class”
• Therefore, the sub class is a specialized version of super
class
• The sub class inherits all the data members and methods
of the super class.
5. Example
class A
{
int a,b;
A( )
{
a=0;
b=0;
}
public void showab()
{
System.out.println(“The value of a is”+a);
System.out.println(“The value of b is”+b);
}
}
6. Example cont..
class B extends A
{
int c;
B( )
{
c=0;
}
public void showc()
{
System.out.println(“The value of c is”+c);
}
}
7. Example cont..
class InheritDriver
{
public static void main(String args[])
{
A obj1=new A();
obj1.a=10;
obj1.b=20;
obj1.showab();
B obj2=new B();
obj2.c=30;
obj2.showc();
obj2.b=40;
obj2.a=20;
obj2.showab();
}
}