Java field hiding

青春壹個敷衍的年華 提交于 2019-12-01 08:33:44

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

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

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.

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