我如何在 innerClass 构造函数中调用 outerClass 构造函数
How can i call an outerClass constructor inside an innerClass constructor
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);
}
}
}
当我尝试构建公民时,此代码生成错误
“无法访问 Adresse 类型的封闭实例。必须使用 Adresse 类型的封闭实例来限定分配(例如 x.new A(),其中 x 是 Adresse 的实例)。”
我该如何解决这个问题?谢谢。
您必须将 class 设置为静态并使用“outer.inner”class 符号调用。
即:
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);
}
}
}
主要:
public class Main {
public static void main(String[] args) {
Adresse.citizen a = new Adresse.citizen("a", "a", "a", "a", 1, 1);
}
}
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);
}
}
}
当我尝试构建公民时,此代码生成错误 “无法访问 Adresse 类型的封闭实例。必须使用 Adresse 类型的封闭实例来限定分配(例如 x.new A(),其中 x 是 Adresse 的实例)。”
我该如何解决这个问题?谢谢。
您必须将 class 设置为静态并使用“outer.inner”class 符号调用。
即:
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);
}
}
}
主要:
public class Main {
public static void main(String[] args) {
Adresse.citizen a = new Adresse.citizen("a", "a", "a", "a", 1, 1);
}
}