Home > Software design >  Exception while trying to invoke method, which invokes method from other class through object of sai
Exception while trying to invoke method, which invokes method from other class through object of sai

Time:07-03

In a program I made, I have a class canteen and a meal of the day class. In my meal of the day class there are several methods which I wanna use in my other class, implementing them in that classes' methods without any kind of inheritence.

Therefore, I create objects of the meal of the day class so I can then use said methods from the canteen class. However, whenever I try to call those methods in my main method I always get the same exception no matter what method I use saying "Cannot invoke "cantina.PratoDia.METHODxyz()" because "this.p1" is null", despite the fact that I have a constructor attributing values to p1, p2 and p3. Not sure what is wrong here so help's appreciated.

Leaving both the classes below with constructors and a method from each that are supposed to interact with each other and also the main method.

public class Cantina {

    public PratoDia p1;
    public PratoDia p2;
    public PratoDia p3;

    
    public Cantina(){
        PratoDia p1 = new PratoDia("Carne", 5, 100);
        PratoDia p2 = new PratoDia("Peixe", 6, 60);
        PratoDia p3 = new PratoDia("Dieta", 4, 40);
    }

    
    public void atualizaPreco(int preço){
        p1.setPreço(preço);
        p2.setPreço(preço);
        p3.setPreço(preço);
    }
    
    public static void main(String[] args) {
        Cantina c = new Cantina();
        c.atualizaPreco(10);
    }
    
}

public class PratoDia {
    int preço;
    String nomePrato;
    int numPratos;
    int incPratos;
    int limitePratos;
    int valorTotal;
    int pagamento;

    public void setPreço(int preço){
        this.preço  = preço/100;
    }
    
    public PratoDia(String nomePrato, int preço, int limitePratos){
        this.nomePrato = nomePrato;
        this.preço = preço;
        this.limitePratos = limitePratos;
        System.out.println(nomePrato   ": "   preço);
        numPratos = 0;
        CompraPratoDoDia();
    }
}
    

CodePudding user response:

You defined the variables named p1, p2, and p3 in your global scope. Inside your Cantina constructor, you create new variables, again with the names p1, p2 and p3. By writing the type of the variable before the name, you create a new variable with the same name, overwriting the variable in the parent scope. Because of this, your global p1 is never actually assigned, and has a value of null. Simply remove the type indicators in the constructor, and it should work.

  •  Tags:  
  • java
  • Related