· Inheritance is the process of deriving a new class from an existing class. It is always a good idea to reuse something that already exists rather than writing the same thing from scratch again. The existing class is known as base or parent or super class. The new class is known as derived or child or sub class.
· It is a mechanism to arrange classes in hierarchy model.
· It offers reusability of the code.
· It allows modifications without affecting the existing class.
· Programmer need not write everything from scratch when preparing new classes to extend the features of existing classes.
· A sub class can access only protected or public members of the super class.
Syntax of deriving class:
class base_class
{
……
}
class derived_class extends base_class
{
……
}
Example:
class counter
{
protected int c;
counter()
{
c=0;
}
public void incr()
{
c++;
}
public void show()
{
System.out.println(c);
}
}
class dcounter extends counter
{
public void decr()
{
c--;
}
}
class Test
{
public static void main(String as[])
{
dcounter c1 = new dcounter(); // child class object
c1.incr(); // accessing parent class method
c1.show(); // prints 1
c1.decr(); // accessing its own method
c1.show(); // prints 0
}
}
Explanation:
In the above example, we have derived a class “dcounter” from the existing class “counter”. It enhances the base class “counter” by adding an additional method “decr()”. With the objects of derived class “dcounter” both base class methods and derived class methods are valid.
0 comments:
Post a Comment