Single level Inheritance
class First
{
void display()
{
System.out.println("In Super Class");
}
}
class Second extends First
{
void display()
{
System.out.println("In Sub Class");
}
}
class Singledemo
{
public static void main(String args[])
{
Second s=new Second ();
s.display();
}
}
File Name: - Singledemo.java
Commands:-
javac Singledemo.java
java Singledemo
OUTPUT:-
In Sub Class
NOTE:-
- Here the super class method has been overridden by the subclass method. It is known as method overriding.
- If we want to execute the method present in superclass also then we can use super keyword.
super keyword
1) In a subclass first the superclass constructor is executed.
2) It hides super class variables or methods i.e. method overriding.
PROGRAM: How to use super keyword
class First
{
int a,b;
First(int a,int b)
{
this.a=a;
this.b=b;
}
void display()
{
System.out.println("a value is:"+a);
System.out.println("b value is:"+b);
}
}
class Second extends First
{
int c,d;
Second(int a,int b,int c,int d)
{
super(a,b);
this.c=c;
this.d=d;
}
void display()
{
super.display();
System.out.println("c value is:"+c);
System.out.println("d value is:"+d);
}
}
class Superdemo
{
public static void main(String args[])
{
Second s=new Second (10, 20, 30, 40);
s.display();
}
}
File Name: - Superdemo.java
Commands:-
javac Superdemo.java
java Superdemo
OUTPUT:-
a value is: 10
b value is: 20
c value is: 30
d value is: 40
HOW CONSTRUCTORS ARE INVOKED?
- In a subclass if we use super keyword or not, in a subclass always first the superclass constructor is executed.
PROGRAM: How constructors are invoked
class First
{
First()
{
System.out.println("First Constructor");
}
}
class Second extends First
{
Second()
{
System.out.println("Second Constructor");
}
}
class Third extends Second
{
Third()
{
System.out.println("Third Constructor");
}
}
class Consdemo
{
public static void main(String args[])
{
Third obj=new Third();
}
}
File Name: - Consdemo.java
Commands:-
javac Consdemo.java
java Consdemo
OUTPUT:-
First Constructor
Second Constructor
Third Constructor
Multi-Level Inheritance
PROGRAM:
class Student
{
int rollno;
}
class Marks extends Student
{
double m1,m2,m3;
}
class Average extends Marks
{
double total;
void show()
{
total=m1+m2+m3;
double result=total/3;
System.out.println("Roll Number:"+rollno+" Average is:"+result);
}
}
class Studentdemo
{
public static void main(String args[])
{
Average avg=new Average();
avg.rollno=10;
avg.m1=60.5;
avg.m2=70.5;
avg.m3=80.5;
avg.show();
}
}
File Name: - Studentdemo.java
Commands:-
javac Studentdemo.java
java Studentdemo
OUTPUT:-
Roll Number: 10 Average is: 70.5