内部类(具有类的所有特征)

1.静态内部类:static修饰,为了体现封装。可以访问外部类的静态资源。可以使用外部类类名访问,在类内部可省略类名,静态内部类中可访问外部类的静态成员。类似于静态方法。

package classDemo;

public class classDemo {

	public static void main(String[] args) {
		Foo.Goo ggg=new Foo.Goo();
		ggg=Foo.GetGOO();
		 System.out.println(ggg.GetA());

	}
	
}
class Foo{
	static int a=1;
	static class Goo{
		int GetA(){
			return a;
		}
	}
	static Goo GetGOO(){
		return new Goo();
	}
}
}

2.成员内部类:类似于成员方法。在类体中声明,不使用static,具有类成员特性,也就是说,必须有类的实例才能创建内部类实例。内部类实例可以共享访问外部类的成员变量,很常见。如:链表的节点就可以定义成内部类。

public class classDemo {

	public static void main(String[] args) {
//		Foo.Goo ggg=new Foo.Goo();
//              Foo.Goo ggg=fff.GetGOO();//错误,此为成员类,若想在外部使用,必须先创建Foo对象。但不推荐使用。
		Foo fff=new Foo();
		Foo.Goo ggg=fff.GetGOO();
	}
	
}
class Foo{
	int a=1;
	class Goo{
		int GetA(){
			return a;
		}
	}
	Goo GetGOO(){
		return new Goo();
	}
}
优点:很好的封装性;可以访问外部类的对象。

3.局部内部类:将类声明在方法中,作用域类似于局部变量。很少见。

public class classDemo {

	public static void main(String[] args) {
		class Foo{
			//局部内部类,类似于局部变量,作用域仅当前局部内部类有效
			//很少使用
			int a=1;
			int GetA(){
				return a;//1
			}
		}
		Foo fff=new Foo();
		fff.GetA();
	}
	
}

4.匿名内部类:很常见,必须有基类。可以写在任何位置,匿名类是对原类的一个集成,同时创建了实例。{}就是继承以后的类体。类体中可使用所有类的语法。匿名类不可写构造器。匿名类可以从抽象类或接口继承,必须提供抽象方法的实现。

package classDemo;

import java.util.Arrays;
import java.util.Comparator;

public class classDemo {

	public static void main(String[] args) {
//		Foo fff=new Foo(){};//匿名内部类,对Foo的继承,即Foo的子类
		Foo fff=new Foo(){//可实现继承、覆盖
			public int GetA(){
				return 2;
			}
		};
		System.out.println(fff);//2
		Yoo yoo=new Yoo() {//可通过匿名内部类来实现接口
			public int GetNum(){
				return 2;
			}
		};
		System.out.println(yoo.GetNum());//2
		CharSequence a=new CharSequence() {//字符序列
			
			@Override
			public CharSequence subSequence(int start, int end) {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public int length() {
				// TODO Auto-generated method stub
				return 10;
			}
			
			@Override
			public char charAt(int index) {
				// TODO Auto-generated method stub
				return 'A';
			}
		};
		StringBuilder str =new StringBuilder(a);//根据length与charAt方法生成的字符序列。
		System.out.println(str);//AAAAAAAAAA  10个A
		//对以下字符串数组按照长度进行排序
		String[] strr={"dfsdf","sa","xvsd","wq","sdfsff"};
		Arrays.sort(strr,new Comparator() {//回调
			public int compare(Object o1, Object o2) {//默认compare:返回 大于0 o1>o2;小于0 o1	
}
interface Yoo{
	int GetNum();
}
class Foo{
	int a=1;
	public int GetA(){
		return a;
	}
	public String toString(){
		return Integer.toString(GetA());
	}
}
 
   
  
5.任何内部类都编译成独立的class文件
6.最大的作用是封装,内部类很少在外部使用。


你可能感兴趣的:(JAVA基础)