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

up cast of object

 
guo mark
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
look at the scope.

class Foo{
public void print(){
System.out.println("this is Foo");
}
}
class Fooer extends Test{
public void print(){
System.out.println("this is Fooer");
}
}
public class RunFoo{
public static void main(String [] args){
SubTest subtest = new SubTest();
Test test = subtest;
test.print();
}
}

I thought it would print "Foo" but in fact it printed "Fooer".It seemed that the Fooer is not up cast to Foo,but why?
 
Matthew Phillips
Ranch Hand
Posts: 2676
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is called dynamic binding. When you assign subtest to a variable of type test it does not change the type of the actual object. When you run the print method the JVM runs the print method of the actual object.
 
Lionel Siau
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm confused. What is SubTest ? A subclass of Test? Your above code seems to be missing something.
 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're confused :^)
class Fooer extendes Test not Foo!!!
NICE EXAMPLE CODE
Originally posted by Lionel Siau:
I'm confused. What is SubTest ? A subclass of Test? Your above code seems to be missing something.
 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is something that shows polymorphic functions.
The base reference 's' of class Shape contains a reference to an object of type 'Circle', this is why the Circle.draw() is called.
Dynamic binding has to do with the 'type referenced', not the reference's type!

[ February 27, 2002: Message edited by: Rajinder Yadav ]
 
guo mark
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks all first.Its ture that there are someting wrong with my code,i forget to change Test and SubTest to Foo and Fooer.But i have got the idear,so thanks to all again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic