Let's look at the following simple code snippet in Java.
interface Sum
{
abstract public void showSum();
}
interface Mul
{
abstract public void showMul();
}
abstract class Super implements Sum
{
protected int x;
protected int y;
public Super(int x, int y)
{
this.x=x;
this.y=y;
}
//No error, though the method showSum() of the implementing iterface Sum is commented. Why?
/*public void showSum()
{
System.out.println("Sum = "+(x+y));
}*/
}
final class Calculation extends Super implements Mul
{
public Calculation(int x, int y)
{
super(x,y);
}
public void showSum()
{
System.out.println("Summation = "+(x+y));
}
//If showMul() is commented , it would issue a compile-time error. Why?
public void showMul()
{
System.out.println("Multiplication = "+(x*y));
}
}
final public class Main
{
public static void main(String[] args) throws IOException
{
Scanner s=new Scanner(System.in);
System.out.print("\nEnter a number : ");
int x=s.nextInt();
System.out.print("\nEnter another number : ");
int y=s.nextInt();
Calculation c=new Calculation(x,y);
c.showSum();
c.showMul();
}
}
Since the interface Sum containing only one method showSum();
is being implemented by the abstract class Super , there should be necessary for the abstract class Super to implement that method showSum();
. The compiler however doesn't complain at all and the program is working well with no problem at all. Why?
Similarly, the non-abstract final class Calculation is implementing the Mul interface and contains the actual implementation of the method showMul();
presented in it's implementing interface. In case, if this method showMul()
in the class Calculation is commented, it issues a compile-time error. Why is the same thing not applicable to that abstract class Super?