我有自己的类,它扩展了 Activity。我还有另一堂课,它扩展了我的第一堂课。如何从头等舱的二等舱获取数据?这是更好理解的模式:class1 扩展了 Activity,class2 扩展了 class1。现在我想从 class1 中获取一些来自 class2 的数据。我怎样才能做到这一点?
问问题
73 次
3 回答
2
您可以在类 1(父级)中设置一个属性并从类 2 分配它
class A {
protected int a;
}
class B extends A {
void method() {
a = 1;
}
}
于 2013-01-09T14:58:45.527 回答
0
You can get data from derived class upstream into parent class by overriding the getter:
abstract class A {
protected abstract int getX();
void doThis() {
int x = getX();
}
}
class B extends A {
@Override
protected int getX() { return 17; };
}
This is useful if the derived class must provide some values as there are no reasonable defaults. The class that fails to do this (does not implement the abstract getter method) simply will not compile, and the error message will be the clear hint that should be done. With assignable inner fields, most you can do is to check already at runtime.
于 2013-01-09T15:45:27.793 回答
0
class A {
private int x = 5;
protected int getX() {
return x;
}
protected void setX(int x) {
this.x = x;
}
public void print() {
// getX() is used such that
// subclass overriding getX() can be reflected in print();
System.out.println(getX());
}
}
class B extends A {
public B() {
}
public static void main(String[] args) {
B b = new B();
b.setX(10);
b.print();
}
}
于 2013-01-09T15:04:36.640 回答