是否可以使用扩展超类方法参数的参数覆盖超类方法? [英] Is it possible to override a superclass' method with a parameter extending the superclass' method parameter?

查看:22
本文介绍了是否可以使用扩展超类方法参数的参数覆盖超类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的课程:

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

我能否指定 A 的子类,以便它使用更具体的某物"类覆盖 setSomething 方法?这就是我想要做的:

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
    }

目前我在A班做这样的事情:

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);

如果 SuperSomething 的类型不适合这些类,B 类和 C 类会在 checkClass 方法中抛出异常.

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.

我已经尝试过使用上面的确切方法签名,但是子类方法不会覆盖超级方法,我想我真的在问:有没有办法在超类的定义中指定一个方法,在编译时检查超类的子类的 setSomething 方法中允许的对象类型?

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?

推荐答案

您可以通过指定类型可以是 Something 或其子类之一来使 A 类泛型(我已经将setSomething 方法抽象,但您可以根据需要提供实现).

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

然后强制类型 T 成为您想要在子类中使用的特定类.

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

这篇关于是否可以使用扩展超类方法参数的参数覆盖超类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆