[英]Assign weaker access to method overriding from superclass
I have a Class called Module
which has a Method onEnable();
我有一个名为
Module
的类,它有一个方法onEnable();
Now i have a class called Config
and want to make the onEnable();
现在我有一个名为
Config
的类并且想要使onEnable();
method private
because there is a predefined acting and a class extending Config
should'nt be allowed to change the behaviour.方法
private
因为有一个预定义的行为和一个扩展Config
的类不应该被允许改变行为。
Is there any way to do this?有没有办法做到这一点?
Example例子
class Module{
public void onEnable(){
}
}
A class extending Module which is allowed to use onEnable
:允许使用
onEnable
扩展模块的类:
class HelloWorldModule{
@Override
public void onEnable(){
System.out.println("Hello, World!");
}
}
Now the config Class, where i want that onEnable
is private so that Classes which extend Config cannot!现在配置类,我希望
onEnable
是私有的,以便扩展配置的类不能! Override onEnable
:覆盖
onEnable
:
class Config{
@Override
private void onEnable(){
}
}
So NOW, a class named ProgrammConfig
which extends Config
cannot override onEnable
.所以现在,一个名为
ProgrammConfig
的类扩展了Config
不能覆盖onEnable
。
However, this is not working because you cannot override a public
method to a private
method.但是,这不起作用,因为您无法将
public
方法覆盖为private
方法。
By declaring a method as public
, you are saying that it should be possible to call said method on every instance of this class, including subclasses.通过将方法声明为
public
,您是说应该可以在此类的每个实例上调用所述方法,包括子类。 Declaring a method as private
in a subclass doesn't make sense, and is thus not allowed.在子类中将方法声明为
private
没有意义,因此是不允许的。
Now, if you're concerned about subclasses overriding the method, you can declare the method as final
to prevent this:现在,如果您担心子类会覆盖该方法,则可以将该方法声明为
final
以防止出现这种情况:
class Config extends Module{
@Override
public final void onEnable(){}
//Whatever
}
You cannot solve this using inheritance.您无法使用继承解决此问题。 If
Config
is a subclass of Module
, then it must provide all functions of Module
with (at most) the same access restrictions.如果
Config
是Module
的子类,那么它必须为Module
所有功能提供(至多)相同的访问限制。 Think of a subclass as a specialized version of the superclass: It can do everything the superclass can, likely more, but never less.将子类视为超类的特殊版本:它可以完成超类所能做的一切,可能更多,但绝不会更少。
Still you can implement a Config
class as desired.您仍然可以根据需要实现
Config
类。 Just skip subclassing, and instead use a private field of type Module
like so:只需跳过子类化,而是使用
Module
类型的私有字段,如下所示:
class Config {
private Module module;
public Config() {
module = new Module();
}
public int SomeFunctionFromModuleYouWantToExpose() {
return module.SomeFunctionFromModuleYouWantToExpose();
}
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.