Java does not provide an explicit way to implement multiple-inheritance i.e. a class can never extend multiple classes. But, this can be achieved (simulated) using interfaces. This is possible because of two reasons:
· A class can implement multiple interfaces
· A class can simultaneously extend a class and implement one or more interfaces
The forms of the above two are shown below:
1. interface A { …. } interface B { .… } class C implements A, B { …. } | 2. class A { …. } interface B { .… } class C extends A implements B { …. } |
The following program illustrates how interfaces can be used to simulate multiple inheritance. The program has an interface named Allowance and a class named Employee. The class named EmpSal extends Employee and implements Allowance. Thus bringing an effect that the class takes multiple inheritance.
interface Allowance
{
int DA = 2000;
int HRA = 3000;
}
class Employee
{
private int empno;
private String ename;
public void getdata(int eno,String n)
{
empno=eno;
ename=n;
}
public void show()
{
System.out.println("Empno:" +empno);
System.out.println("EName:" +ename);
}
}
class EmpSal extends Employee implements Allowance
{
private double sal;
public void getdata(int eno,String n, double s)
{
super.getdata(eno,n);
sal=s;
}
public void totalsalary()
{
super.show();
System.out.println("Total Sal:" + (sal+DA+HRA));
}
}
class Test
{
public static void main(String as[])
{
EmpSal e1=new EmpSal();
e1.getdata(7369,"Ravi",12000);
e1.totalsalary();
}
}
Output:
Empno: 7369
EName: Ravi
Total sal:17000
0 comments:
Post a Comment