package oop.demon01.demon10; public class Outer { private int id = 10; public void out(){ System.out.println("这是外部类的方法"); } public class Inner{ public void in(){ System.out.println("这是内部类的方法"); } //获得外部类的私有属性、方法 public void getID(){ System.out.println(id); } } } -------------------------- package oop.demon01.demon10; public class Application { public static void main(String[] args) { //new Outer outer=new Outer(); //通过外部类来实例化内部类~ Outer.Inner inner = outer.new Inner(); inner.in(); inner.getID(); } }
package oop.demon01.demon10; public class Outer { private static int id = 10; public void out(){ System.out.println("这是外部类的方法"); } public static class Inner{ public void in(){ System.out.println("这是内部类的方法"); } } }
注意:
package oop.demon01.demon10; public class Outer { } //一个Java类中可以有多个class类,但是只能有一个 public class class A{ public static void main(String[] args) { } } ....
package oop.demon01.demon10; public class Outer { //局部内部类(在方法里面写的类) public void method(){ class Inner{ } } }
package oop.demon01.demon10; public class Test { public static void main(String[] args) { //没有名字初始化类,不用实例保存到变量中~ new Apple().eat();// 1 //Apple apple=new Apple(); 没有输出结果的 UserService userService = new UserService() { //接口需要重写 @Override public void Hello() { } }; } } class Apple{ public void eat(){ System.out.println("1"); } } interface UserService{ void Hello(); }