JAVA基础 | 内部类的分类与实例(210115)

JAVA基础 | 内部类的分类与使用实例(210115)

【1】成员内部类(在类中定义的内部类)

class Outerr{
	public void print() {
		System.out.println("这里是外部类");
	}
	public class Inter{
		public void printt() {
			System.out.println("这里是内部类"+"\n下面是被调用的外部类方法");
			print();
		}
	}
	public void aaa(){
		Inter in=new Inter();  //外部类内部直接定义创建
		in.printt();
	}
}

public class BroInter {
	public static void main(String[] args) {
		//Outerr.Inter in=new Outerr().new Inter();
		Outerr out=new Outerr();
		Inter in=out.new Inter();
		//以上是两种对内部类的创建方式 都需要借助外部类去创建内部类
		in.printt();
	}
}

【2】静态内部类(用static修饰的成员内部类)

//静态内部类
class Outer{
	public void print(){
		System.out.println("静态内部类");
	}
	public static class Inter{
		int r=1;
		public void CountArea() {
			System.out.println(Math.PI*Math.pow(r, 2));
		}
	}
	public void test() {
		Inter in=new Inter();  //静态内部类的类内的声明创建调用
		in.CountArea();
	}
}

public class StaticInter {
	public static void main(String[] args) {
		Outer.Inter in=new Outer.Inter();
		in.CountArea();
		//静态内部类的类外部声明创建调用
		Outer out=new Outer();
		out.test();
	}
}

【3】局部内部类(方法中定义的内部类)

class People{
	public People() {}
	public void print() {
		System.out.println("这里是People类");
	}
}

class Man extends People{
	public Man() {}
	public People getWoman() {
		class Woman extends People{
			public Woman() {}
			public void print() {
				System.out.println("这是一个内部类");
			}
		}
		return new Woman();
	}
}

public class PartOfInterTwo {
	public static void main(String[] args) {
		Man man=new Man();
		People p=man.getWoman();
		//p.print();  无法调用因为是上转型对象(当时People类没有try()方法)
		p.print();  //People的try()方法被 Man类中的成员方法中的局部内部类重写了 !!还能调用使用!!
	}
}

【4】匿名内部类(多用于Swing编程中)

button2.addActionListener(  
      new ActionListener(){  
      public void actionPerformed(ActionEvent e) {  
           System.out.println("点击了button2");  
          }  
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值