I want to know whether the statements sc=sbc; Superclass sc1=(Superclass)sbc; are same or not,If same can anybody explain me.

Andyjr Robinson

Greenhorn

Posts: 6

posted 11 years ago

Assuming that you've missed the "extends Superclass" off the Subclass definition by accident: Yes they are the same.

What is happening here ?

A new Superclass object is created and referenced by variable "sc" and a second variable "sbc" is created which references a new Subclass object. Two objects and a reference to each of them.

Then the assignment results in the Subclass object being referenced by the "sc" variable. This is quite fine because a Subclass "is a" Superclass. Following this assignment we can no longer reference the object originally referenced by "sc" - the Superclass object - and it will be garbage collected in due course. We have one object on the heap and two references to it.

The Superclass sc1=(Superclass)sbc line creates another reference as "sc1" to the same original Subclass object. Again this assignment works because a Subclass "is a" Superclass. We now have one object on the heap and three references to it.

I realise that the code given is example; but just to be clear, the original Superclass object need not have been created since it was never used and the cast on the last line is not actually required, then main() becomes akin to what is actually happening:

Subclass sbc=new Subclass(); Superclass sc=sbc; Superclass sc1=sbc;

Niranjan Prasad

Ranch Hand

Posts: 62

posted 11 years ago

sc=sbc; Superclass sc1=(Superclass)sbc;

If both the above does the same work,then y the concept Superclass sc1=(Superclass)sbc; came as sc=sbc is very much fine,i am mean it is simple. Can u explain me the story behind the Superclass sc1=(Superclass)sbc;

Niranjan

Layne Lund

Ranch Hand

Posts: 3061

posted 11 years ago

The are the same because "sb=sbc" is doing the cast behind the scence (i.e. the cast is implicit). In "Superclass sc1=(Superclass)sbc;", the cast is explicit. I don't know if there is much of a story to tell because they do the same thing.