Doubt in the number of Object(s) created
Please see the code below
package chap2.queries;
class Superclass{
publicstaticfinalint x= 17;
publicvoid isObj(){
if(thisinstanceof Object){
System.out.println(this.toString());
System.out.println(this.x);
}
}
}
publicclass Subclassextends Superclass{
publicstaticfinalint x=5;
void isSubclassHasObject(){
if(thisinstanceof Object){
System.out.println(this.toString());
System.out.println(this.x);
isObj();
}
}
publicstaticvoid main(String[] args){
Subclass sub =new Subclass();
sub.isSubclassHasObject();
}
}
The output of the above program is
chap2.queries.Subclass@119c082
5
chap2.queries.Subclass@119c082
17
My queries are:
1.How many object(s) were created in the memory for the above program?
2.Please note that the "System.out.println(this.toString());" in Superclass gave a output referring to the Subclass object. But when "this.x" was used in Superclass,the instance variable 'x' of the Superclass 17 is getting displayed
rather than 5. why is it so?
I kindly request you all the reply these questions
[2464 byte] By [
Sansofta] at [2007-11-27 6:58:01]

Yes, the runtime class of the object is Subclass. However, the compile-time type of the reference (this) is Superclass, and that is what determines which x member variable to use.
The only thing that's determined at runtime by the class of the object (rather than at compile time by the type of the reference) is which class' version of a non-static, non-private, non-final method to invoke.
jverda at 2007-7-12 18:35:28 >

> > The question arises whether any object for
> superclass
> > is created implicitely?
>
>
> There is one object. It is a Subclass. It is also a
> Superclass. I am a man. I am also a human, a mammal,
> an engineer, and a father. But there's only one of me.
If there is only one object of Subclass, how does it show two different x values ? Perhaps only one object, but two member 'x' ? If it is only one object of Sublcass, it always should point to Subclass and should print '5' ?
> If there is only one object of Subclass, how does it
> show two different x values ?
There are two independent x variables that just happen to have the same name--super's and sub's. Because the sub IS-A super, everything that exists in the super also exists in the sub. Which of the two x values we see depends on what the declared type of the reference is through which we access them.
> Perhaps only one
> object, but two member 'x' ?
Yes.
jverda at 2007-7-12 18:35:28 >
