Java field hiding

泄露秘密 提交于 2019-12-04 01:42:55

问题


In the following scenario:

class Person{
    public int ID;  
}

class Student extends Person{
    public int ID;
}

Student "hides ID field of person.

if we wanted to represent the following in the memory:

Student john = new Student();

would john object have two SEPARATE memory locations for storint Person.ID and its own?


回答1:


Correct. Every class in your example has its own int ID id field.

You can read or assign values in this way from the sub classes:

super.ID = ... ; // when it is the direct sub class
((Person) this).ID = ... ; // when the class hierarchy is not one level only

Or externally (when they are public):

Student s = new Student();
s.ID = ... ; // to access the ID of Student
((Person) s).ID = ... ; to access the ID of Person



回答2:


Yes, as you can verify with:

class Student extends Person{
    public int ID;

    void foo() {
        super.ID = 1;
        ID = 2;
        System.out.println(super.ID);
        System.out.println(ID);
    }
}



回答3:


Yes, that is correct. There will be two distinct ints.

You can access Person's int in Student with:

super.ID;

Be careful though, dynamic dispatch doesn't happen for member fields. If you define a method on Person that uses the ID field, it will refer to Person's field, not Student's one even if called on a Student object.

public class A
{
    public int ID = 42;

    public void inheritedMethod()
    {
        System.out.println(ID);
    }
}

public class B extends A
{
    public int ID;

    public static void main(String[] args)
    {
        B b = new B();
        b.ID = 1;
        b.inheritedMethod();
    }
}

The above will print 42, not 1.



来源:https://stackoverflow.com/questions/10154348/java-field-hiding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!