このクラスを作成したとしましょう:
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
sを台無しにするでしょうか?
クラスで宣言されたフィールドと同じ名前のパラメーターを受け取った場合にのみ必要です。
public class Foo {
int x;
int y;
public Foo(int x) {
this.x = x; //here is necessary
y = -10; //here is not
}
}
もう1つの奇妙なシナリオは、サブクラスがスーパークラスのフィールドをシャドウイングする場合です。次に例を示します。
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チュートリアル。フィールドを隠す。このようなシナリオは避ける必要があるため、これは奇妙なことに注意してください。技術的には可能ですが、コードの読み取りと保守が困難になります。これに関するさらに詳しい情報:Javaクラスで使用される変数シャドウイングとは何ですか?
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加