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

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

How can i make a method with call access only inside the child class?

问题

我想要赋予一个方法仅允许子类和当前类调用的访问权限。
例如:

  1. public class Parent {
  2. something void mySetterMethod(int input) {
  3. this.something = input;
  4. }
  5. }
  6. public class Child extends Parent {
  7. mySetterMethod(otherInput);
  8. }

但是这对于以下情况不应该起作用:

  1. public class SomeClassInSamePackage() {
  2. public static void main(String[] args) {
  3. Parent parent = new Parent();
  4. parent.mySetterMethod(input);
  5. }
  6. }
英文:

I want to give a method an access that only the child classes and the current class can call.
For example:

  1. public class Parent{
  2. something void mySetterMethod(int input){
  3. this.something = input;
  4. }
  5. }
  6. public class Child extends Parent{
  7. mySetterMethod(otherInput);
  8. }

but this should not be able to work for:

  1. public class SomeClassInSamePackage(){
  2. public static void main(String[] args){
  3. Parent parent = new Parent();
  4. parent.mySetterMethod(input);
  5. }

答案1

得分: 1

作为一般建议,优先选择组合而非继承

  1. public class Parent {
  2. public void mySetterMethod(int input){
  3. this.something = input;
  4. }
  5. }
  6. public class Child {
  7. private final Parent parent = new Parent();
  8. ...
  9. parent.mySetterMethod(otherInput);
  10. ...
  11. }

你也可以选择不从同一个包中调用它。

作为历史记录,Java 1.0 曾有 private protected,尽管显然存在错误。

英文:

As a general piece of advice prefer composition over inheritance.

  1. public class Parent {
  2. public void mySetterMethod(int input){
  3. this.something = input;
  4. }
  5. }
  6. public class Child {
  7. private final Parent parent = new Parent();
  8. ...
  9. parent.mySetterMethod(otherInput);
  10. ...
  11. }

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:

确定