Hello!

Please explain why in this code a method from class A is called, it’s logical that B. should be called.

public class App2 { public static void main ( String[] args ) { A a = new B(); a.method (2.0); } } class A{ void method(Number n) { System.out.println ("Number"); } } class B extends A{ void method(Double a){ System.out.println ("DOUBLE"); } } 
  • ((B) a) .method (2.0); and if so? - Gorets
  • It works as expected, but I still don’t understand why my version is wrong. =) - user12726
  • early, late binding? - Gorets
  • mm, more precisely, you can? - user12726 5:46 pm

1 answer 1

early, late binding?

That's not the point. The bottom line is that Java does not support the covariance of arguments in inheritance. Because B inherits А , and Double inherits Number , the method() in child class B does not overlap the parent. Otherwise, it would violate the principle of substitution of Barbara Liskov .

Imagine that you still have a class C this type:

 class С extends A{ void method(Integer a){ System.out.println ("INTEGER"); } } 

Since Integer inherited from Number , such a declaration would also be covariant in the argument. Now let's mentally try to execute the code:

 A a = new С(); a.method (2.0); 

And there would be a problem. From the point of view of class A, argument 2.0 is adequate, but from the point of view of class C, it is not. Therefore, to ensure the safety of Java types, it does not allow overriding parent methods in child classes in this way.

  • and if the arguments of the methods are the same? - Gorets
  • 2
    If the arguments in both class A and class B were of the same type, then the overlap and the code A a = new B () would work; a.method (2.0); would display the word DOUBLE - Nofate
  • And if constants, instead of methods? - Gorets
  • Many thanks, quite clearly and clearly explained - user12726