• Post Reply Bookmark Topic Watch Topic
  • New Topic

please help out about object reference...  RSS feed

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Display
{
void display()
{
System.out.println("hi");
}
}
class Disp1 extends Display
{
void disp1()
{
System.out.println("hi1");
}
}
class Dem

{
public static void main(String [] arg)
{
Display b=new Disp1();//this compile fine
Disp1 a=new Display();//y dis wont compile?

}
}
in above "b" reference know about only members of Display in Disp1 object so it compiles fine even reference "a" know about both den why it give compile error?
please help me...
 
author
Sheriff
Posts: 23306
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

shankar dengi wrote:
Display b=new Disp1();//this compile fine
Disp1 a=new Display();//y dis wont compile?



A Disp1 object IS-A Display. The reverse is not necessary true. And in this example, is definitely not true.

Henry
 
shankar dengi
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Henry Wong wrote:

shankar dengi wrote:
Display b=new Disp1();//this compile fine
Disp1 a=new Display();//y dis wont compile?



A Disp1 object IS-A Display. The reverse is not necessary true. And in this example, is definitely not true.

Henry

I dint understood please explain me in detail..
 
Sheriff
Posts: 21185
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's replace Display and Disp1 with Animal and Cat.
 
shankar dengi
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Rob Prime wrote:Let's replace Display and Disp1 with Animal and Cat.

ya but how it works internally?
 
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From a practical sense, if the compiler allowed you to assign a reference to a Display instance to a Disp1 reference variable as in:
you could call the method a.disp1(), which is in the Disp1 class - not the Display class. But the instance you created is a Display. So at runtime, the JVM would at best throw an exception and at worst, crash.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!