Java inheritance extends Program

Java is Object Oriented Programming and it implements Object oriented programming by Inheritance.
We implementation of Inheritance in java, we have to use extends keyword of java. In example we will explain how to use inheritance in java program. Inheritance use the properties of other class in current class.
Suppose in a class parent we declare variable and we can use this variable in child class

InheritanceParent.java

public class InheritanceParent
{
  public String abc=null;
  public String xyz=null;

  public void printOutput()
  {
    System.out.println("Output of Inheritance  :"+abc);
    System.out.println("Output of Second Inheritance  :"+xyz);
  }
}

InheritanceChild.java

public class InheritanceChild
{
  public static void main(String[] args)
  {
    InheritanceParent ip=new InheritanceParent();

    ip.abc="This is inheritance java program";
    ip.xyz="This is child class where extends used";

    ip.printOutput();
  }
}

Compiling and running of this classes

C:\>javac c:\InheritanceParent.java

C:\>javac c:\InheritanceChild.java

C:\>java -classpath . InheritanceChild

Output

Output of Inheritance :This is inheritance java program
Output of Second Inheritance :This is child class where extends used

Second example with extends

InheritanceParent.java

public class InheritanceParent
{
  public String abc=null;
  public String xyz=null;

  public void printOutput()
  {
    System.out.println("Output of Inheritance  :"+abc);
    System.out.println("Output of Second Inheritance  :"+xyz);
  }
}

InheritanceChild.java

public class InheritanceChild extends InheritanceParent
{
  public void parentMethod()
  {
      abc="This is inheritance java program";
      xyz="This is child class where extends used";

      printOutput();
  }
  public static void main(String[] args)
  {
      InheritanceChild ic=new InheritanceChild();
      ic.parentMethod();
  }
}

Compiling and running of this classes

C:\>javac c:\InheritanceParent.java

C:\>javac c:\InheritanceChild.java

C:\>java -classpath . InheritanceChild

Output

Output of Inheritance :This is inheritance java program
Output of Second Inheritance :This is child class where extends used

Bookmark  

 

One Response to “Java inheritance extends Program”

  1. jack says:

    class test
    {

    int a,b;
    void getdata(int x, int y)
    {

    a=x;
    b=y;

    }

    void sum()
    {
    System.out.println(”sum = “+(a+b));
    }

    }

    class test1 extends test

    {

    int c,d;
    void getdata()

    {
    c=20;
    d=30;
    }

    void sum()
    {
    System.out.println(”sum = “+(a+b));

    }

    }

    class temp
    {
    public static void main(String args[])

    {

    test t1 = new test();

    t1.getdata();
    t1.sum();

    test1 t2 = new test1();

    t2.getdata();
    t2.sum();

    }
    }

Leave a Reply

Security Code:

 

  Random Post