| Author |
Object assignments
|
Rahul Bhosale
Ranch Hand
Joined: Mar 10, 2005
Posts: 77
|
|
Please take a look at the following code. Consider all interfaces and classes are well defined. I was expecting the o/p to be java.lang.Object but printed out class StackImpl. In the assign statement how is the destination class representing obj (java.lang.Object) being modified to the source class(StackImpl)?
|
RB
|
 |
navneet shrivastava
Ranch Hand
Joined: Jul 09, 2004
Posts: 39
|
|
/////////////////////////////////////////////// code: ---------------------------------------------------------------------------- Object obj = new Object(); line1 StackImpl stack = new StackImpl(); line2 obj = stack; // no compilation error because sub-type assignment to super-type is valid. line3 System.out.println(obj.getClass()); line4 ---------------------------------------------------------------------------- I was expecting the o/p to be java.lang.Object but printed out class StackImpl. In the assign statement how is the destination class representing obj (java.lang.Object) being modified to the source class(StackImpl)? /////////////////////////////////////////////// from line3 onwards object 'obj' will point to the assigned 'StackImpl' object 'stack'. In line4 "obj.getClass()" calls the method on 'stack' object (ie of type 'StackImpl'). so as output system gives classtype as 'StackImpl' thanks, Nav
|
+nav
|
 |
Jesse Torres
Ranch Hand
Joined: Mar 25, 2004
Posts: 985
|
|
Originally posted by Rahul Bhosale: Please take a look at the following code. Consider all interfaces and classes are well defined. I was expecting the o/p to be java.lang.Object but printed out class StackImpl. In the assign statement how is the destination class representing obj ( java.lang.Object) being modified to the source class(StackImpl)?
The reference type is of type Object but the actual object that is executing is of type StackImpl.
|
 |
Rahul Bhosale
Ranch Hand
Joined: Mar 10, 2005
Posts: 77
|
|
|
So, to know what class an object represents you invoke the getClass() method. how would you know the type of object? i know you can look up at the declaration, but is there any way at runtime that will let the code know what type an object is of?
|
 |
Nikhilesh Fonseca
Ranch Hand
Joined: Aug 23, 2004
Posts: 57
|
|
Can we look at this as a simple case of method overriding.. I kno you havent defined getClass in your class so maybe every class has a a getClass method so when u try ure given code you are overriding the getClass of object and calling the getclass of your subclass.
|
 |
 |
|
|
subject: Object assignments
|
|
|