Nullpointerexception do not know how to solve

Asked

Viewed 49 times

-1

I’m making a house class and a door class, and in the house class I’m declaring 3 doors and when I’m going to run gives Nullpointerexception, could someone give me a light

class of my door

package introducaoclasses;

public class Porta {

 boolean aberta;
 String cor;
 int dx, dy, dz;

 public void abrePorta() {
    this.aberta = true;
 }

 public void fechaPorta() {
    this.aberta = false;
 }

 public void pinta(String nova) {
    this.cor = nova;
 }

 public boolean estaAberta() {
    return this.aberta;
 }
}

My house

package introducaoclasses;

 public class Casa {

 Porta porta1, porta2, porta3;
 String cor;

 public void pintarCasa(String Cor) {
    this.cor = Cor;
 }

 public int quantasPortasEstaoAbertas() {
    int cont = 0;
    if (porta1.estaAberta()) {
        cont++;
    }
    if (porta2.estaAberta()) {
        cont++;
    }
    if (porta3.estaAberta()) {
        cont++;
    }
    return cont;
 }
}

My main class

package introducaoclasses;

  public class IntroducaoClasses {

  public static void main(String[] args) {
    Casa nova = new Casa();
    nova.porta3.abrePorta();
  }

}
  • 3

    You’re not instantiating the doors in any time, you could do this in the class builder Casa.

1 answer

2


In your class Casa, you didn’t charge the doors. Do this:

package introducaoclasses;

public class Casa {

    private Porta porta1 = new Porta();
    private Porta porta2 = new Porta();
    private Porta porta3 = new Porta();
    private String cor;

    public void pintarCasa(String novaCor) {
        this.cor = novaCor;
    }

    public int quantasPortasEstaoAbertas() {
        int cont = 0;
        if (porta1.estaAberta()) {
            cont++;
        }
        if (porta2.estaAberta()) {
            cont++;
        }
        if (porta3.estaAberta()) {
            cont++;
        }
        return cont;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.