Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1023
  • Last Modified:

In Java, why the compilation fails if we use reference variable of type Object?

public class HorseTest
{
      public static void main(String [] args)
      {
            class Horse
            {
                  public String name;
                  public Horse (String s)
                  {
                        name = s;
                  }
            }
            
            Object obj = new Horse("Zippo");
            System.out.println(obj.name);
      }
}

Why compilation error occurs in this line "Object obj = new Horse("Zippo");"? I already know if I use Horse obj = new Horse("Zippo"), then it will be fixed. I just want clear explanation why using reference variable of type Object will cause problems?

Thanks in Advance :)
0
techbro
Asked:
techbro
  • 5
1 Solution
 
for_yanCommented:
In this case it fails on the println operator because you use
vriable name outside of cass Horse
but Object obj = new Horse(name); does not
fail
0
 
for_yanCommented:
No sorry, that was wron sateemnt - it really fails on println, but...
0
 
for_yanCommented:
Yes, if fails on println beacuse iit cannoy itrepret obj.name
You need first to cast obj to Horse
0
 
for_yanCommented:
this would compile:


public class HorseTest
{
      public static void main(String [] args)
      {
            class Horse
            {
                  public String name;
                  public Horse (String s)
                  {
                        name = s;
                  }
            }

            Object obj = new Horse("Zippo");
            System.out.println(((Horse)obj).name);
      }
}
0
 
for_yanCommented:
Variable obj belongs to class Object, and the latter does not
have variable "name", it is only class Horse has variable "name".
Therefore when compiler encounters obj.name it is puzzled - you first need
to cast obj to class Horse and then you can use its variables.

And because you created obj as an instance of Horse cast will work,
of obj would be instance of some unrelated class, then the actual casting operation
(Horse)obj would have raised cast Exception
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now