steven smith steven smith - 1 year ago 110
Java Question

java this in parent and child not working as expected

I'm misunderstanding something really basic with inheritance.
I have a parent class:

public class Parent {
String s = "Parent";
Parent () {}
String getS() {
return this.s;

and a child class:

public class Child extends Parent {
String s = "Child";
Child() { }

Main is like:

Parent parent = new Parent();
Child child = new Child();
Log.e(TAG, "parent:" + parent.getS());
Log.e(TAG, "child:" + child.getS());

I expect parent.getS() to return "Parent" and child.getS() to return "Child" but both return "Parent." Doesn't the method prefix determine the 'this' for the method when called this way?

Thank you
Steve S.

Answer Source
  • Your getS() methods from parent class is inherited in Child class and hence it is available for Child object.
  • Overriding is only for methods and not for instance variables.
  • So even if you define a new variable with same name, it will not take effect as it will not be overridden
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download