子类里继承的方法为什么会去使用父类的prvate属性?

请直接看我精简后的代码:


public class HomeTest {

    private String home = "This is HOME";


    public void printHome() {

        System.out.println(home);

    }

}


public class SmallHomeTest extends HomeTest {

    

    private String home = "This is SMALL HOME";

    

}


public class Entry {


    public static void main(String[] args) {

        SmallHomeTest small = new SmallHomeTest();

        small.printHome();

    }

}

这里的运行结果是This is HOME,而不是"This is SMALL HOME",也就是说,子类HomeTest调用的继承来的方法printHome()里使用的属性,是父类里的private Home,这点我很奇怪,父类里的private不应该是对子类屏蔽的吗?求解释,谢谢!


萧十郎
浏览 633回答 5
5回答

莫回无

我自己来回答这个问题吧,今天研究了下,可能是我对继承的理解不太对。这里子类SmallHomeTest,虽然继承了父类的HomeTest的printHome()方法,其实仅表示,子类可以以父类的身份去调用父类的printHome()方法,而不是指子类有这个方法。所以说,当编译执行时候,编译器发现子类里的small.printHome()语句时,会先检查子类有没有printHome方法,如果没有,再看其父类有没有,如果有,则是以父类的身份,来调用这个printHome()方法,则里面的home变量是来自父类的private home变量(父类是看不到子类定义的的private home变量的)。

慕桂英4014372

public class Entry {    public static void main(String[] args) {        SmallHomeTest small = new SmallHomeTest();        small.printHome();//........①    }}你①处代码调用的    public void printHome() {        System.out.println(home);    }            用public修饰,这和        public String getHome() {        return home;    }                没区别。

小唯快跑啊

成员变量是私有的,只能够在类的内部被使用。成员方法是公有的,可以被外部调用。类的基本特性。

慕无忌1623718

多态性并不能体现在字段上。&nbsp; &nbsp; &nbsp; &nbsp;0: aload_0&nbsp; &nbsp; &nbsp; &nbsp;1: invokespecial #10&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Method java/lang/Object."<init>":()V&nbsp; &nbsp; &nbsp; &nbsp;4: aload_0&nbsp; &nbsp; &nbsp; &nbsp;5: ldc&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#12&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// String This is HOME&nbsp; &nbsp; &nbsp; &nbsp;7: putfield&nbsp; &nbsp; &nbsp; #14&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Field home:Ljava/lang/String;&nbsp; &nbsp; &nbsp; 10: return&nbsp; public void printHome();&nbsp; &nbsp; Code:&nbsp; &nbsp; &nbsp; &nbsp;0: getstatic&nbsp; &nbsp; &nbsp;#21&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Field java/lang/System.out:Ljava/io/PrintStream;&nbsp; &nbsp; &nbsp; &nbsp;3: aload_0&nbsp; &nbsp; &nbsp; &nbsp;4: getfield&nbsp; &nbsp; &nbsp; #14&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Field home:Ljava/lang/String;&nbsp; //这里getfield #14就是上面putfield #14 ,内容是死的。&nbsp; &nbsp; &nbsp; &nbsp;7: invokevirtual #27&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Method java/io/PrintStream.println:(Ljava/lang/String;)V&nbsp; &nbsp; &nbsp; 10: return

BIG阳

就近原则。printHome()方法是父类的方法,printHome()里成员变量的使用优先访问父类的成员变量。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java