0

Let's say I created this class:

public class Panel extends JPanel{
    private JTextBox textBox;
    public Panel(){
        this.textBox = new JTextBox(10);
        add(this.textBox);
    }
}

And in my main:

public class Main{
    public static void main(String[] args){
        Panel panel1 = new Panel();
        Panel panel2 = new Panel();
    }
}

In the class Panel, is it necessary to call this at every line, or can I leave it away? Or would it mess up the Panels?

ikhebgeenaccount
  • 353
  • 6
  • 20

1 Answers1

5

It is only necessary when you receive parameters that have the same name of the fields declared in the class:

public class Foo {
    int x;
    int y;
    public Foo(int x) {
        this.x = x; //here is necessary
        y = -10; //here is not
    }
}

Another weird scenario is when a subclass shadows a field from the super class. Here's an example:

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
    }
}

More info about the latter: Java Tutorial. Hiding Fields. Note that this is weird because you should avoid such scenarios. It is technically possible but makes the code harder to read and to maintain. Even more info on this: What is variable shadowing used for in a Java class?

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • 1
    +1 - Answer could be improved by referencing the phenomenon by it's technical name '**shadowing**' - '*when you receive [or create] parameters that have the same name of the fields declared in the class*' – Rudi Kershaw Aug 18 '14 at 15:59
  • 1
    @Rudi good point. Added it into my answer. – Luiggi Mendoza Aug 18 '14 at 16:04
  • By making the argument to `Foo` constructor `final` it will be even more obvious that `this` is needed. Otherwise it will not even compile. – maba Aug 18 '14 at 16:45