| Author |
up cast of object
|
guo mark
Ranch Hand
Joined: Oct 20, 2001
Posts: 43
|
|
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?
|
meet once ,love every while
|
 |
Matthew Phillips
Ranch Hand
Joined: Mar 09, 2001
Posts: 2676
|
|
|
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.
|
Matthew Phillips
|
 |
Lionel Siau
Greenhorn
Joined: Feb 27, 2002
Posts: 12
|
|
|
I'm confused. What is SubTest ? A subclass of Test? Your above code seems to be missing something.
|
 |
Rajinder Yadav
Ranch Hand
Joined: Jan 18, 2002
Posts: 178
|
|
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.
|
<a href="http://www.rajindery.com" target="_blank" rel="nofollow">Rajinder Yadav</a><p>Each problem that I solved became a rule which served afterwards to solve other problems. --Rene Descartes
|
 |
Rajinder Yadav
Ranch Hand
Joined: Jan 18, 2002
Posts: 178
|
|
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
Joined: Oct 20, 2001
Posts: 43
|
|
|
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.
|
 |
 |
|
|
subject: up cast of object
|
|
|