简体   繁体   English

父类的私有成员用作公共成员函数的参数

[英]Private member of parent class is used as a public member function's parameter

if I have following inheritance relationship.如果我有以下继承关系。

class product {
  product(int param) {};
  ...
}

class parent {
  private int secret;
  ...
  parent() {
    secret = 5; //for example; in real world it is set by complicated computation. 
  }
  public create() {
    return new product(secret);
  }
}

now I need to extend parent class, as现在我需要扩展父类,因为

class childProduct {
  childProduct(int param) {};
  ...
}

class child extends parent {
  child() {
    super();  
  }

  @Override
  public public create() {
    return new childProduct(secret);
  }
}

Now it gets problem by secret is private so I cannot access it in child.现在它因秘密而受到问题是私有的,所以我无法在孩子中访问它。

I resolved this problem by making secret protected .通过设置 secret protected解决了这个问题。

class parent {
  protected int secret;

However I think there is a elegant way to do it.但是我认为有一种优雅的方法可以做到这一点。

Anyone knows?有谁知道?

Thanks.谢谢。

However I think there is a elegant way to do it.但是我认为有一种优雅的方法可以做到这一点。 Anyone knows?有谁知道?

if you need to access a parent's member from a child implementation, then making that member protected IS the elegant way to do it.如果您需要从子实现访问父成员的成员,那么使该成员受保护一种优雅的方式。

Making a member private is to avoid sharing it with the world, including children.将成员设为私有是为了避免与世界共享,包括儿童。 Making it protected is to avoid sharing it with the world, but share it with children (aka keep it in the family).保护它是为了避免与世界分享它,而是与孩子分享它(也就是将它留在家庭中)。 Making it public, is to share it with the world.公开,就是与世界分享。

You might expose the parent's member using a getter, either a protected getter or public, depending on how secret is your secret, and also on whether you want to decouple parent's members from child's members.您可以使用受保护的 getter 或公开的 getter 公开父成员的成员,具体取决于您的秘密的秘密程度,以及您是否希望将父成员与子成员的成员分离。

But accessing the parent's member by making it protected is just perfectly fine, and right, and elegant.但是通过保护它来访问父成员的成员是非常好的,正确的,优雅的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM