Question

In the below example I encountered java.lang.NullPointerException

Brief overview: Class STANDALONE is related to class FACULTY by composition, because STANDALONE has an instance variable that holds a reference to a FACULTY object. I am trying to utilize the use of Composition and getting the below error. Please advice.

FYI: This is the piece of the code where I have the problem.

 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:

Exception in thread "main" java.lang.NullPointerException
    at first_.standalone.facultyStuff(standalone.java:22)
    at first_.MainOne.main(MainOne.java:13)
Était-ce utile?

La solution

This means faculty member is null in your standalone instance. You need to initialize it. You may want to e.g. add a constructor to standalone and initialize the faculty in there.

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

Autres conseils

faculty variable is not initlalized.

You declare the faculty variable but you never initialize it.

public faculty faculty;

After this faculty hasn't been explicitly initialized. Since it's an instance variable Java automatically initializes it to be null.

You probably want to do something like this instead:

public faculty faculty = new faculty();

Or initialize it in the constructor:

public class standalone {
    public faculty faculty;

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

    public void facultyInfo(){

        faculty.someMethod();}
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top