接口、多态练习题

输出下面程序结果:

interface A{}

class B implements A
{
    public String func()
    {
        return "func";
    }
}
class Demo
{
    public static void main(String[] args)
    {
        A  a = new B();
        System.out.println(a.func());
    }
}

运行结果:The method func() is undefined for the type A
分析:A a = new B();实现了多态,此时父类的引用指向子类的对象,
相当于:

动物 a=new 狗();//这就为向上转型 a.发声(); // 对象a可以使用动物中的发声()或其他方法,但不可以调用狗的方法。 A a
= new A();实例化一个父类的对象a 动物 a=new 狗();狗b=(狗)a;//这里是向下转型 这时b可调用动物类未被重写的方法和狗类所有方法(包括重写动物类的方法)

当调用a.func()时,不能调用b中的方法,由于A中没有此方法,所以找不到(The method func() is undefined for the type A)

解决办法:
在接口中添加func();声明

interface A{
    public String func();
    }

或者把B向下转型

        A  a = new B();
        B b = (B) a;//向下转型
        System.out.println(b.func());

类似的有

public class Demo10_3 {
    static AA get()
    {
        return new BB();
    }
    public static void main(String[] args)
    {
        AA a=get();  //new B();
        //BB bb=(BB)a;
        System.out.println(a.test());
        //System.out.println(bb.test());
    }
}
interface AA{
    //public String test();
    }
class BB implements AA
{
    public String test()
    {
        return "yes";
    }
}

猜你喜欢

转载自blog.csdn.net/dz77dz/article/details/81393636