0

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.

Lahiru Ashan
  • 767
  • 9
  • 16
steven smith
  • 1,519
  • 15
  • 31

3 Answers3

1
  • 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
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
  • See here for more: http://stackoverflow.com/questions/772663/having-2-variables-with-the-same-name-in-a-class-that-extends-another-class-in-j – MordechayS Oct 21 '16 at 06:11
0

You should create a getter method i.e. getS() in the Child class to retrieve "Child" when you call child.getS() in your main method. In this way, you override the getS() method that was inherited from the Parent class.

Nadim Baraky
  • 459
  • 5
  • 18
0

The way you would set the s-member in the parent-portion of a child-class, would be to offer a protected constructor (it could, of course, also be public):

protected Parent(String s) { this.s = s; }

which sets the string to the given value. You would then call this constructor as the first call in your child-constructor with

super("Whatever you want");

midor
  • 5,487
  • 2
  • 23
  • 52