inheritance - Java implementation of this - calling a Parent class method to utilizing Child class data member -


this question regarding implementation decision of super , this in java. consider,

parent class contains variable name , method getname()

public class parent {      protected string name = "parent";      protected string getname(){         return this.name;     } } 

and child class inherits parent class has own name variable

public class child extends parent {      protected string name = "child";      protected void printnames() {         system.out.println("parent: " + super.getname());         system.out.println("child: " + this.getname());     }      public static void main(string[] args) {          child c = new child();         c.printnames();     } } 

output:

parent: parent child: parent 

from output, can see that: when method getname() invoked child class super context, returns "parent", when invoked this context, again returns "parent"

if method present in parent class, data members same access modifier present in both,

why shouldn't this.getname() child class return "child" because is-a parent has getname() method

update question not how "child" printed or overriding, implementation decision of this core java team, , intended them.

fields not overridable methods are, fields can hidden or not. this refers current object of type parent in method parent#getname() such value of variable name defined in parent or potentially parent class not in sub class child.

here simple code snippet shows idea:

child child = new child(); // show variable name of class child system.out.println(child.name); // show variable name of class parent this.name  // in getname method system.out.println(((parent)child).name); 

output:

child parent 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -