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

纵然是瞬间 提交于 2019-12-02 08:14:30

问题


Say I have a class like so:

abstract class Something {}

And it has a hierachy with classes extending it:

class FirstSomething extends Something {}
class SecondSomething extends Something {}

Then elsewhere I have a class making use of these somethings:

abstract class A {
    public void setSomething(Something something) {
        //Process the something
    }
}

Am I able to specify a subclass of A, so that it overrides the setSomething method, with the more specific "something" classes? This is what I want to be able to do:

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

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

At the moment I am doing something like this in the A class:

public void setSomething(Something something) {
    checkClass(something);
    //Use the something
}
protected abstract void checkClass(Something something);

where the B class and C class throw an exception in the checkClass method if the type of the SuperSomething is not the right one for those classes.

EDIT: I have tried with the exact method signatures as above, but the subclass methods do not override the super's method, I suppose I am really asking: Is there a way to specify a method in the super class' definition, where there is a compile-time check for the types of object allowable in the setSomething method for subclasses of the superclass?


回答1:


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 <T extends Something> {
    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<FirstSomething> {
    @Override
    public void setSomething(FirstSomething something) {
        //Set the something
    }
}

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


来源:https://stackoverflow.com/questions/34297577/is-it-possible-to-override-a-superclass-method-with-a-parameter-extending-the-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!