[英]How do I access the object that's been instantiated from the abstract class's subclass in java?
I would like to be able to access the object that's been instantiated from the abstract class's subclass. 我希望能够访问从抽象类的子类实例化的对象。 Here's an example. 这是一个例子。
// A.java
public abstract class A {
public int getNewNo() {
int newNo = <Instance of B in this example here>.getNo() + 2;
return newNo;
}
}
// B.java
public class B extends A {
public int getNo() {
return 2;
}
}
// C.java
public class C {
public C(A a) {
System.out.println("The number is "+a.getNewNo());
}
}
// example.java
public void main(String args[]) {
B b = new B();
C c = new C(b);
// should now print out "The number is 4"
}
Is this possible? 这可能吗?
Thanks. 谢谢。
Try: 尝试:
// A.java
public abstract class A {
public abstract int getNo();
public int getNewNo() {
int newNo = getNo() + 2;
return newNo;
}
}
public abstract class A {
public int getNewNo() {
int newNo = getNo() + 2;
return newNo;
}
abstract int getNo();
}
Will do the job. 会做的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.