如何创建一个仅在子类内部可调用的方法?

huangapple go评论65阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年3月4日 06:55:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/60516721.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定