Java-使用'super'关键字 [英] Java - using the 'super' keyword

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

问题描述

一个简单的问题.我创建了一个名为Tester1的类,该类扩展了另一个名为Tester2的类. Tester2包含一个名为"ABC"的公共字符串.

Simple question. I made a class called Tester1 which extends another called Tester2. Tester2 contains a public string called 'ABC'.

这是Tester1:

public class Tester1 extends Tester2
{
    public Tester1()
    {
         ABC = "Hello";
    }
}

如果我改为将第5行更改为

If I instead change line 5 to

super.ABC = "Hello"; 

我仍然在做同样的事情吗?

am I still doing the exact same thing?

推荐答案

是.您的对象中只有一个ABC变量.但是请不要首先公开字段.字段应该几乎总是私有的.

Yes. There's only one ABC variable within your object. But please don't make fields public in the first place. Fields should pretty much always be private.

如果您也在Tester1中声明了变量ABC,则然后会有所不同-Tester1中的字段会隐藏Tester2中,但使用super仍将引用Tester2中的字段.但是也不要这样做-隐藏变量是使代码无法维护的一种非常快捷的方法.

If you declared a variable ABC within Tester1 as well, then there'd be a difference - the field in Tester1 would hide the field in Tester2, but using super you'd still be referring to the field within Tester2. But don't do that, either - hiding variables is a really quick way to make code unmaintainable.

示例代码:

// Please don't write code like this. It's horrible.
class Super {
   public int x;
}

class Sub extends Super {
    public int x;

    public Sub() {
        x = 10;
        super.x = 5;
    }

}

public class Test {
    public static void main(String[] args) {
        Sub sub = new Sub();
        Super sup = sub;
        System.out.println(sub.x); // Prints 10
        System.out.println(sup.x); // Prints 5
    }
}

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

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