user3034861
user3034861

Reputation:

Why does the following inherited method is using super class member

Excuse me for my ignorance. The following code outputs

A1 has name A1
B1 has name A1

But I am expecting

A1 has name A1
B1 has name B1

as String name is redefined in the sub-class. Can anyone explain?

Code Snippet:

public class Client {
    public static void main(String[] args) {
        A1 a = new A1();
        A1 b = new B1();

        System.out.println(a.greeting() + " has name " + a.getName());
        System.out.println(b.greeting() + " has name " + b.getName());
    }
}


class A1 {
    String name = "A1";

    String getName() {
        return name;
    }

    String greeting() {
        return "class A1";
    }
}


class B1 extends A1 {
    String name = "B1";

    String greeting() {
        return "class B1";
    }
}

Upvotes: 0

Views: 78

Answers (3)

Mabdullah
Mabdullah

Reputation: 1013

Here is an Oracle JavaDoc that explains overriding and hiding with Java in more details.

http://docs.oracle.com/javase/tutorial/java/IandI/override.html

also see this SO article, about overriding Java instance variables

Is there a way to override class variables in Java?

I think this should help explain why this is happening, it primarily has to do with how you are instantiating your variables.

Upvotes: 0

undefined
undefined

Reputation: 1364

You don't override getName, so the one from B1 uses A1 implementation, which returns a field name from A1 and has no access to name in B1. As stated before, this is called variable hiding.

Upvotes: 1

Kevin Workman
Kevin Workman

Reputation: 42174

By declaring a variable in your subclass with the same name as a variable declared in a parent class, you're hiding the variable in the parent class. The variable in the child class is a different variable than the variable with the same name in the parent class. You might try something like this:

class B1 extends A1 {
    public B1(){
       name = "B1";
    }

    String greeting() {
        return "class B1";
    }
}

Upvotes: 2

Related Questions