1 package CHAP1; 2 3 public class Login { 4 5 private String username="admin"; 6 private String password="123456"; 7 //相当于login成员 8 //ValidateCredentials验证类(Login的内部类) 9 /*static*/ class ValidateCredentials{ 10 public void validate() { 11 if(username.equals("admin") && (password.equals("123456"))) { 12 System.out.println("登录成功!"); 13 14 } 15 } 16 } 17 } 18 //定义测试类 19 //静态方法类名调用,实例方法对象调用 20 class test { 21 public static void main(String[] args) { 22 Login l=new Login();//先创建外部类对象 23 //再用外部类创建内部类的对象 24 Login.ValidateCredentials v=new Login().new ValidateCredentials(); 25 // Login.ValidateCredentials v=new Login.ValidateCredentials(); 26 v.validate(); 27 } 28 } 29 30
方法局部内部類:
為:
1 package CHAP1; 2 3 public class Login { 4 5 private String username="admin"; 6 private String password="123456"; 7 //方法局部内部類: 8 void Validating () { 9 int i=0; 10 //相当于login成员 11 //ValidateCredentials验证类(Login的内部类) 12 /*static*/ class ValidateCredentials{ 13 public void validate() { 14 //Login l=new Login(); 15 if(username.equals("admin") && (password.equals("123456"))) { 16 System.out.println("登录成功!"); 17 18 } 19 } 20 ValidateCredentials v=new ValidateCredentials(); 21 v.validate(); 22 }} 23 24 } 25 //定义测试类 26 //静态方法类名调用,实例方法对象调用 27 class test { 28 public static void main(String[] args) { 29 Login l=new Login();//先创建外部类对象 30 //再用外部类创建内部类的对象 31 // Login.ValidateCredentials v=new Login().new ValidateCredentials(); 32 // Login.ValidateCredentials v=new Login.ValidateCredentials(); 33 v.validate(); 34 } 35 } 36 37