2022.3.29 内部类
1 package com.oop.demo13; 2 3 public class Outer { 4 private int id = 10; 5 public void out(){ 6 System.out.println("这是外部类的方法"); 7 } 8 9 //内部类 10 public class Inner{ 11 public void in(){ 12 System.out.println("这是内部类的方法"); 13 } 14 //可以获得外部类的私有属性,私有方法 15 public void getID(){ 16 System.out.println(id); 17 out(); 18 } 19 } 20 21 }
1 package com.oop; 2 3 import com.oop.demo13.Outer; 4 5 //一个项目应该只存在一个main()方法 6 public class Application { 7 public static void main(String[] args) { 8 Outer outer = new Outer(); 9 10 //通过外部类来实例化内部类 11 Outer.Inner inner = outer.new Inner(); 12 inner.in(); 13 inner.getID(); 14 } 15 }
静态内部类
1 package com.oop.demo14; 2 3 public class Outer { 4 private int id = 10; //private static int id = 10; 5 public void out(){ 6 System.out.println("这是外部类的方法"); 7 } 8 9 //静态内部类 10 //和类一起加载,所以不能获得非静态私有属性值,非静态私有属性没有加载,除非变成静态私有属性 11 public static class Inner{ 12 public void in(){ 13 System.out.println("这是内部类的方法"); 14 } 15 } 16 }
1 package com.oop; 2 3 import com.oop.demo14.Outer; 4 5 //一个项目应该只存在一个main()方法 6 public class Application { 7 public static void main(String[] args) { 8 Outer outer = new Outer(); 9 } 10 }
局部内部类
1 package com.oop.demo14; 2 public class Outer { 3 //局部内部类:方法中定义的类,类似局部变量 4 public void method(){ 5 class Inner{ 6 public void in(){ 7 } 8 } 9 } 10 } 11 12 //前面不能带public,一个java文件只能有一个public class,可以有多个class类 13 class A{ 14 //可以写main()方法 15 public static void main(String[] args) { 16 } 17 }
匿名内部类
本质:是一个继承了该类或者实现了该接口的子类匿名对象
1 package com.xing; 2 3 public class Test { 4 public static void main(String[] args) { 5 //匿名内部类作为接口的实现类 6 Dog dog = new Dog(){ 7 @Override 8 public void run() { 9 System.out.println("run"); 10 } 11 }; 12 13 dog.run(); 14 } 15 } 16 interface Dog{ 17 void run(); 18 }
1 package com.oop.demo13; 2 3 public class Test { 4 public static void main(String[] args) { 5 //Apple apple = new Apple(); 6 //没有名字初始化类 7 new Apple().eat();//不用将实例保存到对象中 8 9 new UserServise() {//其实会返回UserServise userServise 10 @Override 11 public void hello() { 12 } 13 }; 14 15 } 16 } 17 class Apple{ 18 public void eat(){ 19 System.out.println("eat"); 20 } 21 } 22 interface UserServise{ 23 void hello(); 24 }

浙公网安备 33010602011771号