开发者

Overriding rules in Java

开发者 https://www.devze.com 2023-04-03 19:38 出处:网络
Here are two examples: public class A { public void foo(A a) { System.out.println(\"in A\"); } } public class B extends A {

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 don't understand how come (1) and (2) are considered to be an overrided method for A's foo(). method number 1 accepts a lower class than the original foo(), I mean that I can't send her any class of A. as I see it, (1) does not extend foo(), but it 开发者_JAVA技巧is still counts as an override- why?( Similar argument for (2), but opposite).

The reason that I made me think that it is overrided is this:

when I'm trying to run

  B b = new B();

  b.foo(b);

It checks if A has a foo that accepts B. since every B is an A, it does have one so it ought to print "in A" and not "in B" because B does not overrides it. but it prints "in B"..


Neither of them override the super class A'a 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 I compile 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 ok to return a subclass from an overriding method. The following compiles without error.

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;
  }
}


For overriding to work, method signatures should be the same. In this case, they aren't because they differ in the arguments they take. They are just member functions with 1,2 being overloads. ( Considering 2 as a typo. It should be foo instead of f )


Neither 1) nor 2) override anything, as you can verify that by adding 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");
    }
}

Neither method will compile, since it doesn't override anything.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号