java - Is it necessary always call this in a constructor? -
this question has answer here:
let's created class:
public class panel extends jpanel{ private jtextbox textbox; public panel(){ this.textbox = new jtextbox(10); add(this.textbox); } }
and in main:
public class main{ public static void main(string[] args){ panel panel1 = new panel(); panel panel2 = new panel(); } }
in class panel
, necessary call this
@ every line, or can leave away? or mess panel
s?
it necessary when receive parameters have same name of fields declared in class:
public class foo { int x; int y; public foo(int x) { this.x = x; //here necessary y = -10; //here not } }
another weird scenario when subclass shadows field super class. here's 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 super class this.y = 10; //updating y field current class } }
more info latter: java tutorial. hiding fields. note weird because should avoid such scenarios. technically possible makes code harder read , maintain. more info on this: what variable shadowing used in java class?
Comments
Post a Comment