NullPointerException I do not know how to solve

-1

I'm doing a house class and a port class, and in the house class I'm declaring 3 ports and when I run NullPointerException gives, could someone give me a light

class of my port

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();
  }

}
    
asked by anonymous 15.08.2018 / 22:02

1 answer

2

In your Casa class, you did not instantiate the ports. 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;
    }
}
    
15.08.2018 / 22:05