Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing abstract methods in a subclass in Java

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
}
like image 385
Master Bob Avatar asked Feb 18 '17 19:02

Master Bob


People also ask

How do you implement an abstract method in a subclass?

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.

Do subclasses have to implement all 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.

Can a subclass be abstract Java?

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 .

Can subclasses be 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.


1 Answers

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 ...
    }
}
like image 96
davidxxx Avatar answered Sep 25 '22 06:09

davidxxx