Java Generics Extends Class Parameter

前端 未结 3 1447
挽巷
挽巷 2021-01-20 08:26

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

public interface Shapes{
//methods here
}

public class ShapeAction implements          


        
3条回答
  •  情歌与酒
    2021-01-20 09:07

    There are two different concepts. When you write

    public class ShapeAction
    

    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
    

    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 extends ShapeAction
    

    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
    
    
    

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

    提交回复
    热议问题