Is it possible to override a superclass' method with a parameter extending the superclass' method parameter?

前端 未结 1 519
长发绾君心
长发绾君心 2021-01-23 11:08

Say I have a class like so:

abstract class Something {}

And it has a hierachy with classes extending it:

class FirstSomething e         


        
1条回答
  •  情话喂你
    2021-01-23 12:02

    You can make the A class generic by specifying that the type can be Something or one of its subclasses (I've made the setSomething method abstract but you can provide an implementation if you want).

    abstract class A  {
        public abstract void setSomething(T something);
    }
    

    Then force the type T to be the specific class you want in your subclasses.

    class B extends A {
        @Override
        public void setSomething(FirstSomething something) {
            //Set the something
        }
    }
    
    class C extends A {
        @Override
        public void setSomething(SecondSomething something) {
            //Set the something
        }
    }
    

    0 讨论(0)
提交回复
热议问题