创建方式1 内部类是非静态的
package com.rl.innerclass; public class OuterClass { private int a; private String age; static String gender; class InnerClass{ private String password; //static String gender1; 要报错(类加载的原因 内部类是一个非静态的 需要new 出来才能初始化, 如果此时用静态的变量不满足这一条件) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } public int getA() { return a; } public void setA(int a) { this.a = a; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
初始化的方式:
(1) 创建外部类 外部类 变量名(out自己指定)=new 外部类();
(2) 内部类创建 外部类.内部类 变量名(in) =out.new 内部类();
public static void main(String[] args) { OuterClass out=new OuterClass(); OuterClass.InnerClass in=out.new InnerClass(); in.setPassword("zhang"); System.out.println(in.getPassword()); }
创建方式2 内部类是静态的
类的定义如下:
package com.rl.innerclass; public class OuterClass2 { private int a; private String age; static String gender; static class InnerClass{ static String gender1; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } public int getA() { return a; } public void setA(int a) { this.a = a; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
初始化方式如下:
public static void main(String[] args) { OuterClass2.InnerClass in=new OuterClass2.InnerClass(); in.setPassword("zhang"); System.out.println(in.getPassword());