首页 > 解决方案 > 覆盖接口中的默认方法并执行接口中的默认方法

问题描述

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

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

我想知道如何在银行界面内的控制台中打印以下内容——贷款()

当默认方法被覆盖时

标签: java

解决方案


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


推荐阅读