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?