替代在 java 中使用不同参数覆盖(这是不可能的) [英] Alternative to overriding with different arguments in java (which is impossible)

查看:52
本文介绍了替代在 java 中使用不同参数覆盖(这是不可能的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临一个设计问题,我认为这应该很常见:

Hi I am facing a design problem which I think it should be quite common:

public abstract class Parent
{
    ...

   public boolean itsOk()
   {
       return true;
   }
   public void execute()      
   { 
       if (itsOk()){
          System.out.println("done");
       }
   }
}

即使参数不同,我也需要能够在从Parent"继承的任何子类中覆盖 itsOK() 函数.

I need to be able to override itsOK() function in any subclass inherited from 'Parent' even if arguments are different.

public class Example extends Parent
{
    public boolean itsOK(int a)
    {
       if (a==1)      return true;
       else           return false;
    }

}

然后当我调用execute时,我希望调用子类的itsOk()方法.

Then when I call execute, I want the subclass' itsOk() method to be invoked.

public static void main(String[] args) {
    Example e=new Example();
    e.execute();
}

如果子类的itsOk() 方法没有参数(如父类的方法),这可以正常工作,所以这是一个重要的情况,但是当参数不同时我该如何实现?

This works ok if the subclass' itsOk() method has no arguments (like the 'Parent's method), so it's an overriding case, but how can I make it when arguments are different?

推荐答案

在这种情况下,我宁愿尝试在父类和子类中使用相同的方法签名,即.真正的覆盖而不是重载.然后,您的参数 a 可以是 Example 类的成员,这将避免需要参数.当然,这在很大程度上取决于其余代码.

In such a case I would rather try to have the same method signature in the parent and the child class, ie. a real overwriting and not an overloading. Then, your parameter a could be a member of the class Example which would avoid the need for a parameter. Of course it strongly depends on the rest of the code.

这篇关于替代在 java 中使用不同参数覆盖(这是不可能的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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