0
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?

2
  • What is "it doesn't work?" What were you expecting to see? Commented Jan 31, 2015 at 0:01
  • i was expecting "this is Alpha" as an output but it prints "this is mustang" Commented Jan 31, 2015 at 0:03

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Welcome. You can omit the display function in your Horse class as well as Horse will inherit that from animal as well. If you found that this answered your question consider accepting the answer.
yes i know..i was just practising. i made the first display function for trying the super reference variable
@VikramSingh How can this answer win against mine??
i am not sure but isn't the default scope package in java??
@StefanFalk because it's better than yours?
|
0

"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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.