定义在另一个类内部的类称为内部类, 或嵌套类. 封装它的类称为外部类.
public class Outer { public static void main(String[] args) { Outer o = new Outer(); o.test(); // 直接访问实例内部类 Outer.Inner i = o.new Inner(); i.display(); } //外部类成员 private int x = 10; private void print() { System.out.println(x); } public void test() { // 访问内部类 Inner i = new Inner(); i.display(); } // 内部类 class Inner { // 内部类成员 private int x = 5; void display() { // 调用外部类成员 System.out.println(Outer.this.x); // 调用外部类成员 Outer.this.print(); // 或者 print(); // 因为仅外部类定义了该方法, 所以可以省略"Outer.this" } } }
// 外部类 public class View { // 外部类成员变量 private int x = 20; // 外部类静态成员 private static int staticX = 10; // 静态内部类 static class Button { void onClick() { // 访问外部类静态成员 System.out.println(staticX); // 编译错误, 静态成员无法访问非静态成员 // System.out.println(x); } } public static void main(String[] args) { // 实例化静态内部类 View.Button button = new View.Button(); button.onClick(); } }
public class Outer { private int value = 10; // final 修饰形参, 如果形参是基本类型, 该形参不可改变; 如果是引用类型, 该形参指向的引用不可改变, 但引用指向的具体值可以改变 public void add(final int x, int y) { int z = 100; // 局部内部类 class Inner { void display() { // 调用外部类成员 int sum = x + z + value; System.out.println(sum); } } // 访问局部内部类 // Inner inner = new Inner(); // inner.display(); // 或者声明匿名对象 new Inner().display(); } public static void main(String[] args) { Outer outer = new Outer(); outer.add(100, 300); } }
原文:https://www.cnblogs.com/fxyy/p/11484500.html