java - Is it necessary always call this in a constructor? -


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 panels?

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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -