假设我创建了这个类:
public class Panel extends JPanel{
private JTextBox textBox;
public Panel(){
this.textBox = new JTextBox(10);
add(this.textBox);
}
}
在我的主要内容中:
public class Main{
public static void main(String[] args){
Panel panel1 = new Panel();
Panel panel2 = new Panel();
}
}
在类里面Panel
,是否需要调用this
在每一行,或者我可以把它放在一边吗?或者它会弄乱 Panel
是吗?
最佳答案
仅当您收到的参数与类中声明的字段同名时才需要这样做:
public class Foo {
int x;
int y;
public Foo(int x) {
this.x = x; //here is necessary
y = -10; //here is not
}
}
另一个奇怪的场景是当子类隐藏父类(super class)的字段时。这是一个例子:
class Bar extends Foo {
int y; //shadows y field in Foo
public Bar(int x) {
super(x); //calling constructor of super class
super.y = -5; //updating y field from super class
this.y = 10; //updating y field from current class
}
}
有关后者的更多信息:Java Tutorial. Hiding Fields 。请注意,这很奇怪,因为您应该避免这种情况。这在技术上是可行的,但使代码更难以阅读和维护。有关此的更多信息:What is variable shadowing used for in a Java class?
关于java - 是否有必要始终在构造函数中调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25367256/