Java中super关键字的范围和用法 [英] Scope and use of super keyword in Java

查看:225
本文介绍了Java中super关键字的范围和用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能使用super关键字访问父类变量?

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


推荐答案

回答原问题很简单:只有一个变量叫做类型。它的初始值被c覆盖。请记住,只有一个对象,所以一个变量。 Prashant的代码创建了第二个变量,显然不会覆盖父类中的原始字符串。

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.

这篇关于Java中super关键字的范围和用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆