Java基础——内部类

时间:2021-09-06 21:58:47   收藏:0   阅读:29

内部类

定义

内部类是定义在类内部的类,它可以访问外部类的成员。

为什么需要内部类

  1. 增强封装,把内部类隐藏在外部类中,不允许其他类访问这个内部类
  2. 增加了代码的维护性

内部类分类

实例内部类

class Outter{
	String name = "Outername";
	
	class Inner{
		
		int age = 10;
		String name = "inname";
		
		void test() {
			String name = "testname";
			System.out.println(name);
			
			System.out.println(this.name);
			
			System.out.println(Outter.this.name);
		}
	}
}
public class Test {
	public static void main(String[] args) {
		
		Outter out = new Outter();
		//System.out.println(out.name);
		//创建实例内部类
		//创建内部类对象当中,会有一个外部类的引用 
		Outter.Inner in = out.new Inner();
		in.test();
	}
}

静态内部类

class Outter{
	static String name = "myxq";
	int age = 10;
	static class Inner{
		static String color = "black";
		int width = 30;
		void test() {
			System.out.println(name);
			System.out.println(new Outter().age);
		}
	}
}

public class Test {

	public static void main(String[] args) {
		//创建静态内部类
		Outter.Inner in =	new Outter.Inner();
		in.test();
		
		//System.out.println(in.width);
		
		//访问静态类当中的静态成员
		//System.out.println(Outter.Inner.color);
	}
}

局部内部类

class Outter{
	
	void myxq() {
		
		final String name = "myxq";
		class Inner{
			void test() {
				System.out.println(name);
			}
		}
		Inner in = new Inner();
		in.test();
		
	}
	
}


public class Test {
	
	public static void main(String[] args) {
		
		new Outter().myxq();
	}
}

匿名内部类

interface IUSB{
	void swapData();
}

class MotherBoard{
	void pluginIn(IUSB u) {
		u.swapData();
	}
}

class Printer implements IUSB{
	public void swapData() {
		System.out.println("打印工作");
	}
}

class KeyBoard implements IUSB{
	public void swapData() {
		System.out.println("打字");
	}
}

class Mouse  implements IUSB {
	public void swapData() {
		System.out.println("鼠标移动");
	}
}

public class Test {
	public static void main(String[] args) {
		
		IUSB m = new Mouse();
		IUSB k = new KeyBoard();
		
		MotherBoard b = new MotherBoard();
		b.pluginIn(m);
		b.pluginIn(k);
		
		//b.pluginIn(p);
		
		b.pluginIn(new IUSB() {
			public void swapData() {
				System.out.println("打印工作");
			}
		});
		
	}
}

原文:https://www.cnblogs.com/lykxbg/p/15218150.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!