Login    New User    Forgot Password    Help      

Inheritance

Java Tutorials

Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.

For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.

Example

// Program no 25
// Simple inheritance
class base
{
int a,b;
        void getdata()
        {
        a=10;
        b=20;
        }
        void showdata()
        {
        System.out.println("Value of a is "+a);
        System.out.println("Value of b is "+b);
        }
}
// inheritance
class drive extends base
{
}
class herit1
{
public static void main(String args[])
{
base b1=new base();
b1.getdata();
b1.showdata();
drive d1=new drive();
d1.getdata();
d1.showdata();
}
}

Output

D:\java\javac herit1.java

D:\java\java herit1

Value of a is 10

Value of b is 20

Value of a is 10

Value of b is 20

Java Tutorials