The main feature OOPs is the reusability. Since java is true object oriented language it supports this feature. It can be done by creating new class from already existing ones. The mechanism of deriving a new class from an old one is called inheritance.
Inheritance is used to create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it.
In the terminology of Java, a class that is inherited is called a superclass or parent class. The class that does the inheriting is called a subclass or child class or derived class. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements.
The inheritance allows subclasses to inherit all the variables and methods of their parents classes.
There are different form of inheritance . All forms of inheritance shown in following figure.
There are different form of inheritance . All forms of inheritance shown in following figure.
class subclassname extends superclassname
{
variables declaration;
methods declaration;
}
According to the above syntax the extends keyword is used to specify the inheritance. The subclass can extends the properties of the superclass. The subclass has its own variables and methods as well as access of the superclass.
The inheritance is used when need to add some more specific properties to the existing class without actually modifying the existing class.
Example,
Example,
// Create a superclass.
class A
{
int i, j;
void showij()
{
System.out.println("i and j: "+i+ " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class Inheritance1
{
public static void main(String args[])
{
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb:");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i,jand k in
subOb:");
subOb.sum();
}
}
Posted by: Ruchita Pandya
No comments:
Post a Comment