Home > front end >  Unable to override generic method in java
Unable to override generic method in java

Time:06-04

abstract class Message <T> {
    abstract <T> void setContent(T content) ;
}
class TextMessage extends Message<String> {
     void setContent(String content) {
     }
}
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

I am getting errors like

Main.java:12: error: TextMessage is not abstract and does not override abstract method setContent(T) in Message class TextMessage extends Message { ^ where T is a type-variable: T extends Object declared in method setContent(T) 1 error

CodePudding user response:

Your method declaration:

abstract <T> void setContent(T content) ;

hides the type parameter declared in class. That causes the error, most probably you don't need that additional type parameter on the method.

CodePudding user response:

The method is abstract. Did you mean to use the class parameter instead?

abstract class Message <T> {
    abstract void setContent(T content) ;
}

class TextMessage extends Message<String> {
     void setContent(String content) {
     }
}

CodePudding user response:

Correct implementation is:

abstract class Message <T> {
    abstract void setContent(T content) ;
}

class TextMessage extends Message<String> {
    @Override
    void setContent(String content) {
        System.out.println(content);
    }
}

class IntegerMessage extends Message<Integer> {
    @Override
    void setContent(Integer content) {
        System.out.println(content);
    }
}

As you see type parameter has been specified in TextMessage and IntegerMessage classes

CodePudding user response:

Not useful
This may help you, you can code on Intellij Idea which could fix your code.

abstract class Message <T> {
    abstract <T> void setContent(T content) ;
}
class TextMessage extends Message<String> {

    <String> void setContent(String content) {
    }
}
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
  • Related