Showing posts with label inheritance in java. Show all posts
Showing posts with label inheritance in java. Show all posts

Friday, 28 December 2018

Inheritance in java | Java Inheritance-Online Help

Inheritance in java:

             Inheritance in Java is the process of creating a new class from an existing class. An existing class(old class) is called a base class or superclass or parent class. The new class is called a subclass or a derived class or child class. Inheritance allows a subclass to inherit all the variables and method of their parent class.


Deriving a subclass:

              Inheritance in Java has a new class which is derived from an existing class is called subclass. The general format of deriving a subclass as follows:
class classname2  extends classname1
{
//body of the classname2
}

here,

  • classname2 is the subclass name.
  • classname1 is the superclass name.
  • class and extends are keywords.
  • The keyword extends indicates, established an inheritance relationship between two classes.
  • If the extends class is omitted from the declaration of a class, the java compiler assumes that an object is its superclass.
  • A class may directly extend only one superclass.


program for Inheritance in java:

class x //super class
{
int a,b;
void showab()
{
System.out.println("The value of a and b:"+a+""+b);
}
}
class y entends x //sub class
{
int c;
void showc()
{
System.out.println("The value of c:"+c);
}
void sum()
{
System.out.println("a+b+c:"+(a+b+c))
}
}
class inheritdemo
{
public static void main(Strin args[])
{
x supob=new x();
y subob=new y();
supob.a=5;
supob.b=10;
System.out.println("superclass:");
supob.showab();
System.out.println()
subob.a=5;
subob.b=15;
subob.c=20;
System.out.println("subclass:");
subob.showab();
subob.showc();
Syste.out.println();
System.out.println("the sum of a,b and c in a subclass:");
subob.sum();
}
}

 The output is:
superclass:
The value of a and b:5 10
subclass:
The value of a and b:5 15
The value of c:20
the sum of a,b and c in a subclass:
a+b+c:40