Multiple Inheritance using Interfaces
We know that in multiple inheritance ,sub classes are derived from multiple super classes.If two super classes have same names for their members(variables and Methods) then which member is inherited into the sub class is the main confusion in multiple inheritance.This is the reason ,Java does not support the concept of multiple Inheritance.
Sample Program:
/**
*
*/
package com.interfaceabhi;
/**
* @author Abhinaw.Tripathi
*
*/
interface Father
{
float height=6.2f;
void height();
}
interface Mother
{
float height=5.2f;
void height();
}
class Child implements Father,Mother
{
@Override
public void height()
{
float ht=(Father.height+Mother.height)/2;
System.out.println("Child Height= " +ht);
}
}
public class MultipleInheritanceUsingInterface
{
public static void main(String[] args)
{
Child ch=new Child();
ch.height();
}
}
Result:
Child Height= 5.7
Callbacks using Interface
Calling a function from another function by passing its memory address is called Callbacks.So Callbacks is achieved in java by using interfaces by sharing its memory address.
Sample Program:
/**
*
*/
package com.interfaceabhi;
/**
* @author Abhinaw.Tripathi
*
*/
interface Tax
{
double statetax();
}
class AP implements Tax
{
@Override
public double statetax()
{
System.out.println("According to Ap Gov..");
return 5000.00;
}
}
class Delhi implements Tax
{
@Override
public double statetax()
{
System.out.println("According to Delhi Gov..");
return 50000.00;
}
}
public class CallBacksUsingInterfaceApp
{
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
Class c=Class.forName(args[0]);
Tax ref=(Tax)c.newInstance();
calculateTax(ref);
}
public static void calculateTax(Tax t)
{
double ct=1000.00;
double st=t.statetax();
System.out.println("Total Tax: " +(ct+st));
}
}