Home > Net >  How can i call an outerClass constructor inside an innerClass constructor
How can i call an outerClass constructor inside an innerClass constructor

Time:11-24

public class Adresse{
    private String rue,ville;
    private int codepostale,numero;

    Adresse(String rue,String ville,int num,int code){
        
        this.rue=rue;
        this.ville=ville;
        codepostale=code;
        numero=num;
        
    }
   class Citizen{
    private String nom,prenom;
        private Adresse adr;
        
        
        Citizen(String nom,String prenom,String ville,String rue,int num,int code)
        {
          this.nom=nom;
          this.prenom=prenom;
          this.adr=new Adresse(rue, ville, num, code);
         
        }
}


}

this code generates an error when i try to construct a citizen "No enclosing instance of type Adresse is accessible. Must qualify the allocation with an enclosing instance of type Adresse (e.g. x.new A() where x is an instance of Adresse)."

how can i fix this? thanks.

CodePudding user response:

You have to make your class static and call with the "outer.inner" class notation.

ie:

    public class Adresse {
    private String rue,ville;
    private int codepostale,numero;

    Adresse(String rue,String ville,int num,int code){

        this.rue=rue;
        this.ville=ville;
        codepostale=code;
        numero=num;

    }
    static class citizen{
        private String nom,prenom;
        private Adresse adr;


    citizen(String nom,String prenom,String ville,String rue,int num,int code){
        this.nom=nom;
        this.prenom=prenom;
        this.adr=new Adresse(rue, ville, num, code);

        }
    }

}

Main:

public class Main {
    public static void main(String[] args) {
        Adresse.citizen a = new Adresse.citizen("a", "a", "a", "a", 1, 1);
    }
}
  • Related