当父类和接口有相同的方法时

                     忽然脑海中出现一个问题,当父类和接口有相同的方法时,去调用这个接口时,会 出现什么情况?

                     于是写了例子

public class Parent {

    public void run(){
        System.out.println(100);
    }
}


public interface InterfaceTest {
    void run();
}

public class Test extends Parent implements InterfaceTest{

        public static void main(String[] args){
            Parent test=new Test();
            test.run();

        }
}

//output
100

Process finished with exit code 0

                  神奇的事情发生了,编译器并没有提示让我去实现接口的方法,这时我想到了应该是我从父类继承的run()方法被

被接口当作我对它run()方法的实现。那么如果我去实现这个方法会怎样?

public class Test extends Parent implements InterfaceTest{

    @Override
    public void run(){
        System.out.println(101);
    }
        public static void main(String[] args){
            Parent test=new Test();
            test.run();

        }
}
//output
101

Process finished with exit code 0

             输入结果和预料的一样,我重写的方法即覆盖了父类的方法,又实现了接口的方法

             如果调用父类方法呢 ?继续尝试

public class Test extends Parent implements InterfaceTest{


    @Override
    public void run(){
        super.run();
        System.out.println(101);
    }
        public static void main(String[] args){
            Parent test=new Test();
            test.run();

        }
}
//output
100
101

Process finished with exit code 0

        这个例子虽然简单,但却让我意识到了很多事,第一,子类继承父类,其实就是拷贝过来一个副本,子类无论对这个副本怎样操作都不会影响父类,第二,多态。我是用Parent 创建的test      这个过程中 new Test()产生的实例被向上转型为Parent ,当test调用run()方法时,它会先去子类里面去找,看看这个方法又没有被重写,如果重写就调用这个方法,如果没有,就调用自己的,至于为什么能找,是向上转型的过程中,父类对象保存了对子类对象的引用

猜你喜欢

转载自blog.csdn.net/qq_33543634/article/details/82152363
今日推荐