• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting of Reference  RSS feed

 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Super {
public void my() {
System.out.println("Super");
}
}

-------------------------------------

public class Sub {
public void my() {
System.out.println("Sub");
}
public static void main(String s[]) {
Super s = new Sub();
s.my();
}
}

-------------------------------------
The output when we execute second program is : Sub

It means calling of a method is depends on object not on reference .

But if sub class does not have same method then ouput is : Super

Because it is visible in Sub class .

If Super class does not have method then we have to cast first before calling method ((Sub)(s)).my();

why ??

Please if possible then post the concept of casting the reference .

I hope it is clear what I am looking for !!!

thanks
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is an example of elementary polymorphism. Here's a nice story introducing polymorphism
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, a super class is often a standalone class. Why should it have a subclass' method? A Dog is an Animal, but why should an Animal have to bark? A Cat is an Animal, does that mean an Animal has to miow? Given an unkown Animal how can you make it utter a sound?
 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks , Now it is clear to me .
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!