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

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

问题描述

说我有这样的课程:

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.

编辑:
我尝试过如上所述的确切方法签名,但子类方法不会覆盖super的方法,我想我真的在问:
有没有办法在超类的定义中指定一个方法,其中有一个编译时检查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 或其子类之一(我已经设置了 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天全站免登陆