Inheritance is a feature of reusing the code.Without starting from scratch we can create a new class(Child,Subclass) having all features of old(Parent,Superclass) in addition to its own features.
Syntax: class Subclass name extends Superclass name
{
//body of sub class
}
Following Code will illustrate the concept:
Code::
class Super
{
int a,b;
void show()
{
System.out.println(a+b);
}
}
class Sub extends Super
{
int c;
void display()
{
System.out.println(a+b+c); // a,b are the members of superclass
}
}
public class Inheritance
{
public static void main(String[] nt)
{
Super ob=new Super();
Sub ob2=new Sub();
ob.a=50;
ob.b=20;
ob2.a=50;
ob2.b=20;
ob2.c=10;
ob.show();
ob2.display();
}
}
Output::
Above example also illustrate the fact that we can use a superclass itself.
Syntax: class Subclass name extends Superclass name
{
//body of sub class
}
Following Code will illustrate the concept:
Code::
class Super
{
int a,b;
void show()
{
System.out.println(a+b);
}
}
class Sub extends Super
{
int c;
void display()
{
System.out.println(a+b+c); // a,b are the members of superclass
}
}
public class Inheritance
{
public static void main(String[] nt)
{
Super ob=new Super();
Sub ob2=new Sub();
ob.a=50;
ob.b=20;
ob2.a=50;
ob2.b=20;
ob2.c=10;
ob.show();
ob2.display();
}
}
Output::
Above example also illustrate the fact that we can use a superclass itself.