-1

So I have the following code :

class Super {
    private String name="super";
    public String name(){
        return this.name;
    }
}
class Sub extends Super {
    private String name = "sub";
}
public class Main {
    public static void main(String[] args) {
        System.out.println(new Sub().name());
    }
}

what I get is as result is : super . I wasnt to know why ?! Isn't the method name() supposed to call this of the object that was called from and since Sub extends Super then it should be able to use it on its members ?!

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
AnotherBrick
  • 153
  • 3
  • 6
  • 14
  • One simple rule to remember: **fields are not polymorphic**, only methods are (unless they are private, final or static). – Pshemo May 15 '16 at 14:32

1 Answers1

1

You're probably thinking that the name member field in Sub should be overriding the name member field in Super. It does not: fields cannot be overridden in Java. Moreover, you've defined both fields as private, meaning that member is only visible to other members of that class (and not members of derived classes or of other classes). So in your code, Super has its own private definition of the name field, and Sub has its own completely different private definition. Neither is aware of the existence of the other.

Standard practice in Java is to use getters and setters to access internal data. If need be, you are then free to override it in derived classes.

TypeIA
  • 16,916
  • 1
  • 38
  • 52