覆盖接口中的默认方法并在接口中执行默认方法

时间:2018-07-15 06:50:07

标签: java

我想通过创建具体实现类的对象来执行接口中默认方法的定义主体,该对象也已覆盖该方法。无论是直接创建具体实现类的对象还是通过动态绑定/多态性,实现类中定义/覆盖的主体都只会被执行。 请参见下面的代码

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();
    } 
}

我想知道如何在控制台中打印以下内容 内部银行业务接口-loan()

当默认方法被覆盖时

2 个答案:

答案 0 :(得分:1)

Banking.super.loan()将调用Banking接口default方法。

答案 1 :(得分: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");
}
}