【问题标题】:Inheritance functions in java [duplicate]java中的继承函数[重复]
【发布时间】:2014-11-19 11:49:28
【问题描述】:

Disabling inherited method on derived class 的副本

这是我的班级代码:

class Parent{
    public bool sum(int a){return true;}

    public int mul(int a){return a*a;}

}

还有另外两个扩展父类的类:

class derived extend parent{
    //here this child can see two methods of parent class and
    //I want just see sum method in here and don't see mul method
}
class derivedb extend parent{
//here this child can see two methods of parent class and
//I want here just see mul method.
}

【问题讨论】:

  • 恕我直言,如果你没有在任何其他地方使用这个父级,你可以为 mul 函数设置私有
  • 我不明白这个问题。你想隐藏 mul 函数你想让 sum 函数在派生类中吗?
  • 请注意,Java 没有“函数”之类的东西,只有“方法”。有人请编辑问题。
  • 如果您希望mul 方法在外部可见但阻止任何子类重新定义它,那么您需要将mul 方法设为final
  • 该死的..错误的副本。应该是stackoverflow.com/questions/5486402/…

标签: java class inheritance


【解决方案1】:

您可以通过在 Parent 类中将 mul 作为私有方法来实现。所以 mul 方法只在 Parent 类中可见

class Parent{
    public bool sum(int a){return true;}

    private int mul(int a){return a*a;}

}

【讨论】:

  • 这是我刚上一节课的时候!
猜你喜欢
  • 2015-06-18
  • 1970-01-01
  • 2021-06-30
  • 2019-05-08
  • 2014-09-15
  • 2015-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多