Reputation: 124
public class HelloWorld
{
public static void main(String []args)
{
Horse obj1=new Horse();
Horse obj2=obj1;
Animal obj3;
obj3=obj2;
obj2.name="Mustang";
obj3.name="Alpha";
obj3.display();
}
}
class Animal
{
String name;
void display()
{
System.out.println("this is "+name);
}
}
class Horse extends Animal
{
String name;
void display()
{
System.out.println("this is "+name);
}
}
Hello,i am a beginner in java so sorry if the question is stupid. This is a simple program in which a reference variable obj2 references another reference variable obj1 of the same type. If I change the instance variable "name" they get change in both as both the reference variable are pointing to the same memory I guess. Now i made another reference variable "obj3" of type Animal which is the super class. I made it reference obj2 and now when I try to change the instance variable "name" using obj3 it doesn't work. Can anyone tell me why this happens?
Upvotes: 0
Views: 95
Reputation: 11020
"I was expecting "this is Alpha" as an output but it prints "this is mustang"".
Well, you have two "buckets" named name
. Depending on the type, you will access one or the other. Since the obj3
reference thinks it's an Animal
, it accesses (and prints) the name
from the super class, Animal
. So that's why obj3
prints "this is mustang" is because it's accessing the name
that is declared inside the Animal
class.
Upvotes: 0
Reputation: 13560
You are defining the member String name in both the super type and the subtype. You should remove the name member from the Horse class.
Upvotes: 1