Scope and use of super keyword in Java

孤街浪徒 提交于 2019-12-04 07:15:45

问题


Why can't I access the parent class variable with the super keyword?

With the below code, the output is:

feline cougar c c   
class Feline {
    public String type = "f ";

    public Feline() {
        System.out.print("feline ");
    }
}

public class Cougar extends Feline {
    public Cougar() {
        System.out.print("cougar ");

    }

    void go() {
        type = "c ";
        System.out.print(this.type + super.type);
    }

    public static void main(String[] args) {
        new Cougar().go();
    }
}

回答1:


The answer to the original question is simple: There is only one variable called type. Its initial value gets overwritten by c. Remember that there is only one object, so one variable. Prashant's code creates a second variable and obviously that one doesn't overwrite the original string in the parent class.



来源:https://stackoverflow.com/questions/45763885/scope-and-use-of-super-keyword-in-java

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