gpt4 book ai didi

java - 如何限制子类修改抽象类中方法的范围?

转载 作者:搜寻专家 更新时间:2023-11-01 01:13:51 26 4
gpt4 key购买 nike

如何限制我的抽象类的实现类将方法的范围从 protected 修改为 public?

例如:假设我有一个抽象类

package com.rao.test;

public abstract class AbstractTEClass {

protected abstract void function1();

protected abstract void function2();


protected void doWork() //I want to call the abstract methods from this method.
{
function1(); //implementation classes will give implementation of these methods
function2();

}

}

现在,我有一个扩展上述抽象类的实现类

package com.rao.test;

public class AbstractTEClassImpl extends AbstractTEClass {

@Override
public void function1() {
// TODO Auto-generated method stub
System.out.println("FUnction1");
}

@Override
public void function2() {
// TODO Auto-generated method stub
System.out.println("Function2");
}


public static void main(String[] args)
{
AbstractTEClassImpl objTEClass = new AbstractTEClassImpl();

objTEClass.doWork();

}

}

注意这里我把实现类中的2个抽象方法的作用域从protected改成了public,如何限制我的实现类修改作用域。
欢迎任何设计更改或建议或模式。

最佳答案

你不能。

重写类总是可以比被重写的方法更多地访问方法。

在此处阅读修饰符部分 http://docs.oracle.com/javase/tutorial/java/IandI/override.html

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa.

关于java - 如何限制子类修改抽象类中方法的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11343763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com