This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
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:
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;
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.