I've made my code as generic as possible to try and help people in the future. My abstract class has a method of the type class and and an input of the type class. In the class that extends the abstract, I try to implement that 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
}
To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass. A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.
The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class. All the methods in an interface are implicitly abstract unless the interface methods are static or default.
Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .
A subclass can be abstract even if its superclass is concrete. For example, the Object class is concrete, but may have an abstract subclass like GeometricObject . A subclass may override a method from its superclass to declare it abstract.
To achieve what you want : associating the type of the argument to the declared class, you could use generics.
abstract class :
public abstract class A <T extends A<T>> {
public abstract T method1(T arg);
}
concrete class :
public class B extends A<B> {
@Override
public B method1(B arg) {
...
return ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With