[英]Use subclass member variable in super class methods?
I have a base class and subclass. 我有一个基类和子类。 Base class has common methods and its implementation which I want to use in subclass but I want to use subclass member variable instead of superclass. 基类具有通用方法及其实现,我想在子类中使用它,但我想使用子类成员变量而不是超类。 I do not want to rewrite the same method in subclass. 我不想在子类中重写相同的方法。 Is there a way in Java to achieve this. Java中有没有办法实现这一目标。
You can use a method to access the member and override it in subclasses. 您可以使用一种方法来访问成员并在子类中覆盖它。
Class A{
public void DoStuff(){
int aux = getResource;
/*cool things with aux*/
}
protected int getResource(){
return internal_member;
}
private int internal_member;
}
Class B extends A{
private int another_member;
@Override
public int getResource(){
return another_member;
}
}
But take into account that this will not prevent people chaging class A from using the member directly, It might be better to create a base class for the members and the getters. 但是要考虑到这不会阻止人们追踪A类直接使用该成员,最好为成员和getter创建一个基类。
Another Option, as some people outlined before is to have the data member in the base class as protected and initialize it in the subclass: 正如前面概述的那样,另一个选择是将基类中的数据成员作为受保护的对象,并在子类中对其进行初始化:
Class A{
public void DoStuff(){
/*cool things with internal_member*/
}
protected List internal_member;
A(){internal_member = /*Set here a value*/}
}
Class B extends A{
B(){internal_member = /*Set a different value here! you can even declare a member and assign it here*/}
}
You can use constructors with arguments if you need. 如果需要,可以将构造函数与参数一起使用。
You could create a protected
setter on the member variable & then override the value of the super's variable within the constructor of the subclass: 您可以在成员变量上创建一个protected
setter,然后在子类的构造函数中覆盖super变量的值:
class Animal {
private String voice = "Oooo";
protected void setVoice(String voice) {
this.voice = voice;
}
public void speak() {
System.out.println(this.voice);
}
}
class Dog extends Animal {
public Dog() {
setVoice("woof");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.