1

I want to execute the defined body of a default method in interface by creating an object of concrete implementation class which has also overridden the method. Whether I create the object of concrete implementation class directly or whether through dynamic binding/polymorphism , the body defined/ overriden in the implementation class is only getting executed. Please see the below code

interface Banking 
{
    void openAc();
    default void loan()
    {
    System.out.println("inside interface Banking -- loan()");
    }

}

class Cust1 implements Banking
{
    public void openAc()
    {
        System.out.println("customer 1 opened an account");
    }

    public void loan()
    {
        // super.loan(); unable to execute the default method of interface 
        //when overridden in implementation class
         System.out.println("Customer1 takes loan");
    }
}//Cust1 concrete implementation class

class IntfProg8 
{

    public static void main(String[] args) 
    {
        System.out.println("Object type=Banking \t\t\t Reference type=Cust1");
        Banking banking = new Cust1();
        banking.openAc();
        banking.loan();
    } 
}

I want to know how to print the following in console inside interface Banking -- loan()

when the default method is overridden

  • The fact of putting the interface name on the left hand side of the object creating has NO effects on the created object. Unrelated: use the @Override annotation when overriding! – GhostCat Jul 15 '18 at 06:58

2 Answers2

1

Banking.super.loan() would call the Banking interface default method.

Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33
  • Generally static methods are called wrt to interface name . I am reading this syntax for the first time interfaceName.super.methodName. I checked and executed the code, it is working , but can you please explain the concept/logic behind it, Thanks in advance – Rahul Arora Jul 15 '18 at 07:43
1
class Cust1 implements Banking {
public void openAc() {
    System.out.println("customer 1 opened an account");
}
public void loan() {
    Banking.super.loan();
    System.out.println("Customer1 takes loan");
}
}
varsh
  • 11
  • 3
  • 1
    Generally static methods are called wrt to interface name . I am reading this syntax for the first time interfaceName.super.methodName. I checked and executed the code, it is working , but can you please explain the concept/logic behind it, Thanks in advance – Rahul Arora Jul 15 '18 at 07:41
  • Please add an explanation. – petezurich Jul 15 '18 at 09:37