Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics Extends Class Parameter

I received an error and I have this structure in my program

public interface Shapes<T>{
//methods here
}

public class ShapeAction<T> implements Shapes<T>{
//Methods and implementations here
}

public class Circle extends ShapeAction<T>{
//Some methods here
}

The error is pointing at class Circle extends Shapes<T> where it says "T cannot be resolved to a type". If I set T to string the error will go away but that also means I can only use one datatype. What should I put inside the <> so that I can use any datatype (String, int, double etc) or did I do this the wrong way?

like image 936
dimas Avatar asked Jun 09 '26 10:06

dimas


1 Answers

There are two different concepts. When you write

public class ShapeAction<T>

this means that you are creating a class which, when instantiated, will be parametrized with some class. You don't know at the time which it will be, so you refer to it just as T.

But when you write

public class Circle extends ShapeAction<T>

this means that you want Circle to be a subclass of ShapeAction parametrized with type T. But what is T? Compiler can't tell that: you declared Circle without any type variables.

You have two options. You can make Circle generic too:

public class Circle<T> extends ShapeAction<T>

This way when you make a new instance of Circle you specify what type it works with, and this extends to the superclass.

And what if you want to specify that ShapeAction can be of any type, but without making the subclass generic? Use Object:

public class Circle extends ShapeAction<Object>

This way Circle stays non-generic, but you can use any data types with the superclass.

like image 112
Malcolm Avatar answered Jun 10 '26 23:06

Malcolm