Implementing abstract methods in a Java subclass

I made my code as universal as possible to try to help people in the future. My abstract class has a method of type type and an input of type type. In a class that extends abstractness, I try to implement this method to no avail. What am I doing wrong?

public abstract class A {
    public abstract A method1(A arg);
}

public class B extends A {
    @Override
    public B method1(B arg) { "...insert code here"} // Error: The method method1(B) must override or implement a supertype method
}
+4
source share
5 answers

To achieve what you want: by associating an argument type with a declared class, you can use generics.

abstract class:

public abstract class A <T extends A<T>> {
    public abstract T method1(T arg);
}

specific class:

public class B extends A<B> {
    @Override
    public B method1(B arg) { 
     ...
      return ...
    }
}
+3
source

. , , , , .

public B method1(B arg) { "...insert code here"} public B method1(A arg) { "...insert code here"}

+2

: , , ; -, .

, :

  • , ( , ); , Object, String, String Object s.

    Java. , , ; , , .

  • , ( , ).

    ; Java . , Java : , ( , ) .

JLS Sec 8.4.8.3.

B: , A, B A, A.method1 A > , B.method1 .

B.method1 A.

+2

A.method1 , , A, method1, A.

B.method1 B, A.

0

Everything you wrote is correct, except for the type of the method arguments, you cannot change the signature of the abstract method of the superclass when overridden in a subclass.

public abstract class A {
    public abstract A method1(A arg);
}

public class B extends A {
    @Override
    public B method1(A arg) { "...insert code here"} // Error: The method method1(B) must override or implement a supertype method
}
0
source

Source: https://habr.com/ru/post/1670188/


All Articles