java - How the super and this keywords work in a subclass method -


this question has answer here:

class feline {     public string type = "f ";      public feline() {         system.out.print("feline ");     } }  public class cougar extends feline {      public cougar() {         system.out.print("cougar ");     }     void go() {         type = "c ";         system.out.print(this.type + super.type);     }     public static void main(string[] args) {         new cougar().go();     } } 

in code output coming feline cougar c c , when changing subclass variable string type = "c" means assigning new string type answer coming feline cougar f f please let me know how , super keyword working in subclass method?

type unqualified name, , refers local variable, parameter, or field.
this.type refers field accessible current class.
super.type refers field accessible base class.

since subclass cougar not have field named type, both this.type , super.type refers type field declared in base class feline. in example, there no difference between this , super.

the statement type = "c "; in method go() unqualified, , since there no local variable or parameter name, refers field type of base class feline. such, type, this.type, , super.type refer 1 , field named type.

if statement in method go() changed string type = "c";, defines differently named local variable. remember, java names case-sensitive, type , type not same name. so, field type retains initialized value of "f ".

if intended change statement in method go() string type = "c";, defines , initialize local variable named type. nature, cannot update field type, since initializer applies newly declared local variable. so, field type retains initialized value of "f ".

if first declare local variable in method go() using string type;, assign original code using type = "c";, unqualified name refers local variable, not field, name. local variable hiding field of same name. so, once again, field type retains initialized value of "f ".


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -