英文:
How can i make a method with call access only inside the child class?
问题
我想要赋予一个方法仅允许子类和当前类调用的访问权限。
例如:
public class Parent {
something void mySetterMethod(int input) {
this.something = input;
}
}
public class Child extends Parent {
mySetterMethod(otherInput);
}
但是这对于以下情况不应该起作用:
public class SomeClassInSamePackage() {
public static void main(String[] args) {
Parent parent = new Parent();
parent.mySetterMethod(input);
}
}
英文:
I want to give a method an access that only the child classes and the current class can call.
For example:
public class Parent{
something void mySetterMethod(int input){
this.something = input;
}
}
public class Child extends Parent{
mySetterMethod(otherInput);
}
but this should not be able to work for:
public class SomeClassInSamePackage(){
public static void main(String[] args){
Parent parent = new Parent();
parent.mySetterMethod(input);
}
答案1
得分: 1
作为一般建议,优先选择组合而非继承。
public class Parent {
public void mySetterMethod(int input){
this.something = input;
}
}
public class Child {
private final Parent parent = new Parent();
...
parent.mySetterMethod(otherInput);
...
}
你也可以选择不从同一个包中调用它。
作为历史记录,Java 1.0 曾有 private protected
,尽管显然存在错误。
英文:
As a general piece of advice prefer composition over inheritance.
public class Parent {
public void mySetterMethod(int input){
this.something = input;
}
}
public class Child {
private final Parent parent = new Parent();
...
parent.mySetterMethod(otherInput);
...
}
You could just not call it from the same package.
As a historical note, Java 1.0 had private protected
, although apparently it was buggy.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论