簡體   English   中英

無法使用Composition訪問類方法?

[英]Can't Access class methods using Composition?

在下面的示例中,我遇到了java.lang.NullPointerException

簡要概述:類STANDALONE通過組合與類FACULTY相關,因為STANDALONE具有實例變量,該實例變量保存對FACULTY對象的引用。 我試圖利用Composition的使用並得到以下錯誤。 請指教。

僅供參考:這是我遇到問題的代碼部分。

 public abstract class person { // getters setters }

 public class faculty extends person {

              public faculty(){super();}

              public void someMethod(){  //some stuff "method calls" }


}

public class standalone {

         //composition has-a relationship

          public faculty faculty;

          public void facultyInfo(){

        // Compiler is complaining about this line
                faculty.someMethod();}
}

public class MainOne {

      public static void main(String[] args) {

         standalone stand = new  standalone();

                //Compiler is complaining about this line 
                  stand.facultyInfo();
    }
}

例外:

Exception in thread "main" java.lang.NullPointerException
    at first_.standalone.facultyStuff(standalone.java:22)
    at first_.MainOne.main(MainOne.java:13)

這意味着在您的standalone實例中, facultynull 您需要初始化它。 您可能想要例如將一個構造函數添加到standalone並在其中初始化faculty

public standalone(){
    this.faculty = new faculty();
}

教師變量未初始化。

您聲明了faculty變量,但從未對其進行初始化。

public faculty faculty;

在此faculty尚未明確初始化之后。 由於它是一個實例變量,因此Java會自動將其初始化為null

您可能想改為執行以下操作:

public faculty faculty = new faculty();

或在構造函數中對其進行初始化:

public class standalone {
    public faculty faculty;

    public faculty() {
        this.faculty = new faculty();  // Now faculty is initialized and useable
    }

    public void facultyInfo(){

        faculty.someMethod();}
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM