Inheritance: Inheritance is a process of creating a new class from the existing class.The existing class is base class/parent class/super class.The derived class is child class/sub class.Java supports only three types of inheritance:
- Single inheritance.
- Multilevel inheritance.
- Hierarchical inheritance.
Static members:The members which one declared with static keyword are called static member.They are belong to class not to instance.They are getting memory space globally at the time of compilation so to access the static members there is no need of objects.Static members are categorized into two types:
- Static data members.
- Static member functions.
Static data members:The data members which one declare with static keyword are called static members and they can be operate by static function or non static function.
Static member functions:Static member functions are operate only static data members.Those data members that are in static function are always be static.
Here is the program of simple calculator using inheritance:
import java.util.*;
class base{
static int a,b; //Declare variables are static
static void add() //Declare method is static
{
//Static data members are call through class and int as a static initial value is zero.
System.out.println("The initial value of static variable as a int is Zero"+"\t"+ base.a);
Scanner input= new Scanner (System.in);
System.out.print("Enter first number"+"\t");
a=input.nextInt();
System.out.print("Enter Second number"+"\t");
b=input.nextInt();
int s=a+b;
System.out.println("The sum of two variables is"+"\t"+s);
}
}
class derived extends base{
static void mul(){
int k; //Data members are always static in static function
k=a*b;
System.out.println("The multiplication of two variables is"+"\t"+k);
}
}
class derived2 extends derived
{
void sub(){
int m;
m=a-b;
System.out.println("The Subtraction of two variables is"+"\t"+m);
}
}
class derived3 extends derived2
{
void div(){
int r;
r=a/b;
System.out.println("The Division of two variables is"+"\t"+r);
}
}
class mains{
public static void main(String args[])
{
derived3 d=new derived3();
//Static function are call through class name as well as object name.
base.add();
d.mul();
d.sub();
d.div();
}
}
You need to save this program with mains.java class name.
You need to save this program with mains.java class name.
Output of program:
No comments:
Post a Comment