0

Why is my java code not working?

I saw on tutorials that classes do not necesarly need the static word, but if I remove the "static" from the class at the line 3, i get a error. I tough that private variables cannot be accessed outside the class, so how is the line 54 not giving a error? Help. https://code.sololearn.com/cOKWtIfUBAAE/?ref=app

27th Sep 2021, 3:19 PM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
3 Answers
+ 2
Well private variables can be accessed by the inner classes. And if you don't use static keyword in inner class you have to create an object for the outer class first and then using that object you have to create the object for inner class public class Program{ public class Factura{ private int pret_intreg; private int pret_mediu_locuinta; private boolean plata; public int getPI(){ return this.pret_intreg; } public int getPM(){ return this.pret_mediu_locuinta; } public boolean getStare(){ return this.plata; } public void setPI(int pret){ this.pret_intreg = pret; } public void setPM(int pret){ this.pret_mediu_locuinta = pret; } public void setStare(boolean stare){ this.plata = stare; } public Factura(){
27th Sep 2021, 4:50 PM
Arun Ruban SJ
Arun Ruban SJ - avatar
+ 2
remaining code from above public Factura(){ this.setPI(50); this.setPM(25); this.setStare(false); } public Factura(int PI, int PM, boolean stare){ this.setPI(PI); this.setPM(PM); this.setStare(stare); } public void scrie_detalii_factura(){ System.out.println("Pret intreg factura: " + this.pret_intreg + "\nPret Mediu factura: " + this.pret_mediu_locuinta + "\nStare factura: " + this.plata); } } public static void main(String []args){ Program obj = new Program (); Program.Factura apa = obj.new Factura(10, 99, true); //Doesn t work if I remove "static" from the factura class. apa.scrie_detalii_factura(); System.out.println(apa.plata); //?? } }
27th Sep 2021, 4:51 PM
Arun Ruban SJ
Arun Ruban SJ - avatar
+ 1
use different way to create object // Factura apa = new Factura(10, 99, true); Factura apa = new Program(). new Factura(10, 99, true);
27th Sep 2021, 4:40 PM
zemiak