I wrote the following code snippet:
class Plane {} class Airbus extends Plane {} public class Main { void fly(Plane p) { System.out.println("I'm in a plane"); } void fly(Airbus a) { System.out.println("I'm in the best Airbus!"); } public static void main(String[] args) { Main m = new Main(); Plane plane = new Plane(); m.fly(plane); Airbus airbus = new Airbus(); m.fly(airbus); Plane planeAirbus = new Airbus(); m.fly(planeAirbus); } }
And the result:
I'm in a plane I'm in the best Airbus! I'm in a plane
No wonder the two first calls are I'm in a plane and I'm in the best Airbus! respectively.
Plane planeAirbus = new Airbus();
The method treats this object as a plane, although the real object is Airbus. Even when I add abstract to class Plane , nothing changes, and the result of the last call is still I'm in a plane
So the question is, why does polymorphism not work in method arguments and calls? Is there any purpose? How it works?
java polymorphism oop
Bartłomiej szałach
source share