![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg7bd3U3RpPwjHhqhnYGi-pBcje0EK3nvwponBSd1IzctIfrAwe22MLm8jwpvx5ZrhKi_oClw6Y6GC1UvQfnalhFXPN7Lof4a-qMYJeO3nG4RX0UEgjnbo8uniMUz8RYy8tfQQMFvPW68hT/s200/sun-java.jpg)
There are four types of inheritance.
*single inheritance : only one super class.
*multilevel inheritance : derived from derived class
*multiple inheritance : more than one super class
*hierarchical inheritance : one super class and more than one derived classes.
In java , multiple inheritance is possible only with the help of interface.We will discuss interface latter.
syntax :
class subclass_name extends super_class{
variable of the class;
methods of the class;
}
extends is a keyword ,which signifies that the propertise of the superclass_name is extended to subclass_name.
//example of inheritance
class employee{
public int emplono , basic ;
public employee(int x, int y){
emplono = x;
basic = y;
}
public void getdata(){
System.out.println(" Employee number : " + emplono );
System.out.println("basic : " + basic );}
}
class total extends employee
{
int days;
total(int x, int y, int z){
super(x, y);
days = z;}
public int salary (){
return basic*days;
}
}
class hiha{
public static void main(String args[]){
total a2 = new total(123,500,25);
a2.getdata();
int z = a2.salary();
System.out.println(" salary : " + z);
}}
super keyword
In java , there is a keyword called as super. Super keyword helps us in two ways , first to call the constructor of the super class.Second it helps the sub classes to access the private(access modifier) data members of the super class.The sub class cannot directly access the variables or other data members that are defined as private (access modifier) in the super class.
In the above program , " super(x, y); " is used to pass arguments in the superclass's constructor employee.
//example: to access the superclass
class start {
int i;
}
class der extends start {
public int i;
public der(int x, int y){
super.i = x;
i = y;
}
public int area (){
return super.i*i;
}}
class star{
public static void main(String args[]){
der a1 = new der(12,5);
int z = a1.show();
System.out.println(" area of rectangle : " + z );
}
}
No comments:
Post a Comment