【问题标题】:How do I access the object that's been instantiated from the abstract class's subclass in java?java - 如何访问从java中抽象类的子类实例化的对象?
【发布时间】:2013-07-19 09:36:23
【问题描述】:

我希望能够访问从抽象类的子类实例化的对象。这是一个例子。

// 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"
}

这可能吗?

谢谢。

【问题讨论】:

    标签: java class instance abstract-class subclass


    【解决方案1】:

    试试:

    // A.java
    public abstract class A {
      public abstract int getNo();
    
      public int getNewNo() {
        int newNo = getNo() + 2;
        return newNo;
      }
    }
    

    【讨论】:

    • 你秒杀我:)
    • @Reddy 你得到了复选标记。多么美好的世界,多么美好的世界:)
    【解决方案2】:
    public abstract class A {
        public int getNewNo() {
            int newNo = getNo() + 2;
            return newNo;
        }
    
        abstract int getNo();
    }
    

    会做的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-27
      • 2021-03-01
      • 1970-01-01
      • 2015-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多