Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

Hiding Fields in Java Inheritance

Within a class, a field that has the same name as a field in the superclass hides the superclass's field.

public class Test {

    public static void main(String[] args) {

        Father father = new Son();
        System.out.println(father.i); //why 1?
        System.out.println(father.getI());  //2
        System.out.println(father.j);  //why 10?
        System.out.println(father.getJ()); //why 10?

        System.out.println();

        Son son = new Son();
        System.out.println(son.i);  //2 
        System.out.println(son.getI()); //2
        System.out.println(son.j); //20
        System.out.println(son.getJ()); //why 10?
    }  
}

class Son extends Father {

    int i = 2;
    int j = 20;

    @Override
    public int getI() {
        return i;
    }
}

class Father {

    int i = 1;
    int j = 10;

    public int getI() {
        return i;
    }

    public int getJ() {
        return j;
    }
}

Can someone explain the results for me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In java, fields are not polymorphic.

Father father = new Son();
System.out.println(father.i); //why 1? Ans : reference is of type father, so 1 (fields are not polymorphic)
System.out.println(father.getI());  //2 : overridden method called
System.out.println(father.j);  //why 10? Ans : reference is of type father, so 2
System.out.println(father.getJ()); //why 10? there is not overridden getJ() method in Son class, so father.getJ() is called

System.out.println();

// same explaination as above for following 
Son son = new Son();
System.out.println(son.i);  //2 
System.out.println(son.getI()); //2
System.out.println(son.j); //20
System.out.println(son.getJ()); //why 10?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...