Is it possible to override a superclass' metho

2020-04-23 03:19发布

问题:

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
    }
}