JAVA语言内部类
什么叫内部类
当两个类属于嵌套关系存在时,嵌套的类—内部类 被嵌套的类叫外部类
Class文件: 外部类名称$内部类名称
例如 Outer$Inner
内部类的分类
1.成员内部类 2.局部内部类 3 静态内部类 4.匿名内部类
为什么java要设计内部类,内部类的存在有什么好处?
内部类加入属性 ----安全性相对较高、设计性更隐秘 节约资源,减少代码的冗余度
成员内部类
和成员变量以及成员方法相同 也是外部类的成员
特点:
1.成员内部类不可以声明静态的成员内部类变量和内部类静态方法
2.成员内部类可以访问外部类的成员变量和成员方法
3.非静态成员方法创建对象直接创建
4.静态成员方法
先创建外部类对象,通过外部类对象去创建内部类对象 最后用内部类对象访问内部类成员方法。
package com.openlab.pojo;
import com.openlab.pojo.Outer.Inner;
public class Outer {
public int i = 0;
public int j = 10;
public int k = 100;
public static int l = 1000;
public class Inner {
public int a = 1;
public int i = 2;
// public static int b = 3;
public void inner_f(){
int i = 101;
System.out.println(a);
System.out.println(i);
System.out.println(l);
System.out.println(this.i);
System.out.println(Outer.this.i);
// f();
// f1();
}
// public static inner_f1(){
//
// }
}
public void f(){
Inner inner = new Inner();
inner.inner_f();
}
public static void f1(){
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.inner_f();
}
}
局部内部类-方法内部类
类在方法的里面 —相当于局部变量
调用: 通过外部类方法的调用 去调用内部类的方法
package com.openlab.pojo;
public class Outer1 {
public int i = 0;
public int j = 10;
public int k = 100;
public static int l = 1000;
public void f(int c){
class Inner{
public int n;
public int a = 1;
public int i = 2;
public Inner(int n) {
this.n = n;
}
public void inner_f1(){
System.out.println(a);
System.out.println(i);
System.out.println(l);
System.out.println(this.i);
System.out.println(Outer1.this.i);
System.out.println(n);
}
}
new Inner(c).inner_f1();
}
public static void f1(){
}
}
匿名内部类
在结构上等同于方法内部类
简单来说 内部类没有名字—无法构造
一般情况下匿名内部类 代码行数都不太多,在业务上讲匿名内部类中的方法业务,只使用一次就够了。
package com.openlab.pojo;
import com.openlab.domain.Person;
public class Test {
public static void main(String[] args) {
Content c = new Content() {// 匿名内部类的开始
@Override
public int m() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void eat() {
// TODO Auto-generated method stub
}
};//匿名内部类的结束
}
}
静态内部类
3.package com.openlab.pojo;
4.
5.import com.openlab.pojo.Outer.Inner;
6.
7.public class Outer {
8.
9. public int i = 0;
10. public int j = 10;
11. public int k = 100;
12. public static int l = 1000;
13.
14. public static class Inner {
15.
16. public int a = 1;
17. public int i = 2;
18. public static int b = 3;
19.
20. public static void inner_f(){
21. int i = 101;
22. System.out.println(a);
23. System.out.println(i);
24. System.out.println(l);
25.
26.// f();
27. f1();
28. }
29. }
30. public void f(){
31. Inner inner = new Inner();
32. inner.inner_f();
33.
34. }
35.
36. public static void f1(){
37.
38. Outer.Inner.inner_f();
39.
40. }
41.
42.
43.}
44.