Scope and use of super keyword in Java

2020-05-10 09:38发布

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

标签: java super
1条回答
别忘想泡老子
2楼-- · 2020-05-10 10:10

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.

查看更多
登录 后发表回答