-1

Hi i create the objects for child class and try to call the child class variables but it called the super class variable both super class and sub class have same class variable name .

In this output name is "Child" is expecting for "o2.name;" but output is "Base".Please explain me clearly...

Daniel Brady
  • 934
  • 3
  • 11
  • 27
Karthick A.S
  • 177
  • 1
  • 13
  • 4
    You can´t override vairables. It simply does acces the first variable `name` that it can acces from the class `ovrriddingBase`. – SomeJavaGuy Sep 22 '15 at 13:57
  • i am creating the object for child class "ovrriddingBase o2=new ovrriddingChild();" then i am try to call the child class variable "name". I am expecting the answer "Child" but i got "Base" – Karthick A.S Sep 22 '15 at 14:01
  • 1
    Please post code snippets, not screenshots. – dimo414 Sep 22 '15 at 14:03
  • Hi kevin, In case i am creating object like "ovrriddingBase o1=new ovrriddingBase();" means output "Base" is correct...but i am create the object for "ovrriddingBase o2=new ovrriddingChild();". – Karthick A.S Sep 22 '15 at 14:05
  • @KarthickA.S Your Variable is declared as `ovrriddingBase`, hence you do acces the methods and variables that are visible within the scope of the class `ovrriddingBase`. – SomeJavaGuy Sep 22 '15 at 14:08
  • Ok Kevin....now i got it thanks – Karthick A.S Sep 22 '15 at 14:09

3 Answers3

4

Variables are not polymorphic in Java; they do not override one another. When you make a variable of the same name in a subclass, that's called hiding. The resulting subclass will now actually have both properties. You can access the one from the superclass with super.var or ((SuperClass)this).var

ankur2908
  • 91
  • 5
3

In Java you don not override fields, you just hide them. At runtime, java checks the reference type of the object you are using and call that variable.

The variables don't even have to be of the same type; they are just two variables sharing a name.

Check this posts:
Overriding member variables in Java
Overriding a super class's instance variables
Is there a way to override class variables in Java?

Community
  • 1
  • 1
David Herrero
  • 704
  • 5
  • 17
1

Java Doesnt support variable overrriding. So when you write :

OverrridingBase o2= new Overridingchild();
System.out.println(o2.name);

JVM will take the reference type of o2 (i.e OverrridingBase) , and will print the value of name of OverrridingBase

Rahman
  • 3,755
  • 3
  • 26
  • 43