DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Java (http://www.daniweb.com/forums/forum9.html)
-   -   doubt on object reference (http://www.daniweb.com/forums/thread201662.html)

purijatin Jul 4th, 2009 12:10 pm
doubt on object reference
 
class A
{
void show()
{
System.out.println("show");
}
}
class B extends A
{
void disp()
{
System.out.println("disp");
}
}
class Prac2
{
public static void main(String args[])
{
A ob = new B();
ob.disp();
}
}


/*this thing shows an error */


now my question is :i thought we can use any object reference which must be above hierchy than the object which we are giving.but then here it shows an error...can some one pl explain object reference in detail because till now i use to think that they are only something like pointers but here they are acting differently

JamesCherrill Jul 4th, 2009 12:36 pm
Re: doubt on object reference
 
The reference variable ob is a ref to type A, which means it can refer to any object of type A or of any sub-type of A.
However, because it is declared as A it can only be used to access members that are defined in A, and there is no disp method in A, so its a compile error.
If you override show in B then you can call ob.show, and the implementation of show from B will be used if ob is actually a reference to a type B, but that's only because show is defined in A.

purijatin Jul 4th, 2009 12:43 pm
Re: doubt on object reference
 
ok i get it now..thanks a lot James


All times are GMT -4. The time now is 10:45 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC