Rule overriding in Java

Here are two examples:

public class A { public void foo(A a) { System.out.println("in A"); } } public class B extends A { public void foo(B b) { // (1) System.out.println("in B"); } public void f(Object o) { // (2) System.out.println("in B"); } } 

I do not understand why (1) and (2) are considered an overridden method for A foo() . method number 1 takes a lower class than the original foo() , I mean that I can not send it any class A. as I see it, (1) does not extend foo() , but it still counts as override-why? (A similar argument for (2), but vice versa).

The reason I made me think it was overridden is this:

when i try to run

  B b = new B(); b.foo(b); 

It checks if A foo that accepts B since each B is A , it has one, so it should print "in A" and not "in B" because B does not cancel it. but he prints "in B".

+4
source share
3 answers

None of them overrides A'a's superclass method.

 class A { public void foo(A a) { System.out.println("in A"); } } class B extends A { @Override public void foo(B b) { System.out.println("in B"); } @Override public void foo(Object o) { System.out.println("in B"); } } 

When compiling the above, I get errors:

 $ javac -g O.java O.java:10: method does not override or implement a method from a supertype @Override ^ O.java:14: method does not override or implement a method from a supertype @Override ^ 2 errors 

But note that it is normal to return a subclass from an override method. The following compilation without errors.

 class A { public A foo() { System.out.println("in A"); return this; } } class B extends A { @Override public B foo() { System.out.println("in B"); return this; } } 
+5
source

To override for operation, the method signatures must be the same. In this case, they are not because they differ in the arguments that they accept. They are only member functions with 1.2 overloads. (Counting 2 as a typo. It should be foo instead of f )

+1
source

Neither 1) nor 2) override anything, as you can be sure to add the @Override annotation:

 public class B extends A { @Override public void foo(B b) { System.out.println("in B"); } @Override public void f(Object o) { System.out.println("in B"); } } 

None of the methods will compile, since it does not cancel anything.

0
source

All Articles