Quantcast
Channel: Java this in parent and child not working as expected - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Java this in parent and child not working as expected

$
0
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.


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>