Suppose you have three classes Ferrari, Toyota and Ford. All these are Cars and can move().
If you wanted to call move() for all 3 objects you should code like this:
But if you had 1 thousand of cars it would be impossible. So you say
And then you can:
It is called an UPCAST. This is one of the major goals of interfaces. Of course, there are lots of other things, you'd better read the Sun Tutorial linked by Fubarable
Java Code:
1 2 3 | Ferrari scaglietti = new Ferrari(); Toyota yaris = new Toyota(); Ford focus = new Focus(); |
Java Code:
1 2 3 | yaris.move(); scaglietti.move(); focus.move(); |
Java Code:
1 2 3 4 5 6 7 | interface Car { void move(); } class Ferrari implements Car { ... public void move() ... } class Toyota implements Car { ... public void move() ... } class Ford implements Car { ... public void move() ... } |
Java Code:
1 2 3 4 5 | Car[] myCars = { ... } for (each car in myCars) { car.move(); } |
No comments:
Post a Comment