Single level inheritance in Java language
In this tutorial, we will discuss the concept of single-level inheritance in Java language
Single level inheritance is one of the techniques in Java. It is easy to understand, a class acquires the properties of (data members and methods) another class. The diagram below indicates that class B extends only from class A. Here, A is the parent class of B, therefore, B is the child class of A.
Single inheritance
The diagram above shows that the school class is the base class or parent class. Data members and methods are properties of the school class. Student class is the child class or derived class and this class acquires the properties of the school class.
Syntex
class Super{
…………
…………
}
class Sub extends Super{
…………
…………
}
Example
program 1
class Base
{
void displayb()
{
System.out.println(“thnis is Base class display”);
}
}
class drived extends Base
{
void displayc()
{
System.out.println(“thnis is drived class display”);
}
public static void main(String args[]){
drived d=new drived();
d.displayb();
d.displayc();
}
}
Program2
class Base1
{
void displayb()
{
System.out.println(“thnis is Base class display”);
}
}
class drived extends Base
{
void displayc()
{
System.out.println(“thnis is drived class display”);
}
}
class simpleinherit{
public static void main(String args[]){
drived d=new drived();
d.displayb();
d.displayc();
}
}
Program 3
class teacher{ //class teacher
float salary=40000;
}
//………………….
class principal extends teacher{ // class principal
float bonus=10000;
public static void main (String args[]){ //main method
principal p=new principal(); //create object
System.out.println(“teacher salary is:”+p.salary);
//access variable of teacher class from this class
System.out.println(“principal bonus is:”+p.bonus);
//access variable of this class
}
}
program 4
class maths2
{
int a; // global variable
public void add(int x, int y){ // create method add
//parameter passing to method add as int a, int b
a=x+y;
System.out.println(“The sum of the x,y:”+a);
}
public void sub(int x, int y){//create method sub
//parameter passing to method sub as int a, int b
a=x-y;
System.out.println(“The different of the x,y:”+a);
}
}
public class calc extends maths2{
public void mul(int x, int y){
a=x*y;
System.out.println(“The multiplication of the x,y:”+a);
}
public static void main (String args[])//main method
{
calc demo=new calc(); //create object
demo.add(34,56); // argument passing
demo.sub(78,54);
demo.mul(78,79);
}