Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting

 
Niranjan Prasad
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Superclass
{
int i;
public void m1()
{
Sytem.out.println("m1() of Superclass is called")
}
}

class Subclass
{
int j;
public void m2()
{
Sytem.out.println("m2() of Subclass is called");
}
}

class Test
{
public static void main(String args)
{
Superclass sc=new Superclass();
Subclass sbc=new Subclass();
sc=sbc;
Superclass sc1=(Superclass)sbc;
}
}

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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic