Java中的重载和隐藏方法 [英] Overload and hide methods in Java

查看:83
本文介绍了Java中的重载和隐藏方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有公共insert()方法的抽象类BaseClass:

i have an abstract class BaseClass with a public insert() method:

public abstract class BaseClass {

 public void insert(Object object) {
  // Do something
 }

}

,它由许多其他类扩展.但是,对于其中的某些类,insert()方法必须具有其他参数,以便它们可以替代而不是覆盖它,而用所需的参数重载基类的方法,例如:

which is extended by many other classes. For some of those classes, however, the insert() method must have additional parameters, so that they instead of overriding it I overload the method of the base class with the parameters required, for example:

public class SampleClass extends BaseClass {

 public void insert(Object object, Long param){
  // Do Something
 }

}

现在,如果我实例化SampleClass类,则有两个insert()方法:

Now, if i instantiate the SampleClass class, i have two insert() methods:

SampleClass sampleClass = new SampleClass();
sampleClass.insert(Object object);
sampleClass.insert(Object object, Long param);

我想做的是隐藏基类中定义的insert()方法,以便只显示重载:

what i'd like to do is to hide the insert() method defined in the base class, so that just the overload would be visible:

SampleClass sampleClass = new SampleClass();
sampleClass.insert(Object object, Long param);

这可以在OOP中完成吗?

Could this be done in OOP?

推荐答案

无法隐藏该方法.您可以这样做:

There is no way of hiding the method. You can do this:

@Override
public void insert(Object ob) {
  throw new UnsupportedOperationException("not supported");
}

但是就是这样.

基类创建合同.所有子类均受该合同约束.这样想吧:

The base class creates a contract. All subclasses are bound by that contract. Think about it this way:

BaseObject b = new SomeObjectWithoutInsert();
b.insert(...);

该代码如何表示它不具有insert(Object)方法?不能.

How is that code meant to know that it doesn't have an insert(Object) method? It can't.

您的问题听起来像是设计问题.要么所讨论的类不应该从所讨论的基类继承,要么该基类不应该具有该方法.也许您可以从该类中除去insert(),将其移到子类中,并让需要insert(Object)扩展它的类和需要insert(Object, Object)扩展那些基础对象的不同子类的类.

Your problem sounds like a design problem. Either the classes in question shouldn't be inheriting from the base class in question or that base class shouldn't have that method. Perhaps you can take insert() out of that class, move it to a subclass and have classes that need insert(Object) extend it and those that need insert(Object, Object) extend a different subclass of the base object.

这篇关于Java中的重载和隐藏方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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