Java内部类是定义在另一个类中的类。使用内部类可以带来一些好处,例如更好的封装、代码组织以及支持多态。以下是Java内部类的一些常见用法:
public
。class OuterClass {
private int data = 10;
class InnerClass {
void display() {
System.out.println("Data from outer class: " + data);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display(); // 输出:Data from outer class: 10
}
}
static
关键字声明的内部类称为静态内部类。静态内部类不能访问外部类的非静态成员,因为它们不依赖于外部类的实例。class OuterClass {
private int data = 10;
static class StaticInnerClass {
void display() {
System.out.println("Data from outer class: " + data);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass.StaticInnerClass inner = new OuterClass.StaticInnerClass();
inner.display(); // 输出:Data from outer class: 10
}
}
class OuterClass {
class InnerClass {
void display() {
System.out.println("Inner class instance");
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display(); // 输出:Inner class instance
}
}
interface MyInterface {
void display();
}
class OuterClass {
class InnerClass implements MyInterface {
@Override
public void display() {
System.out.println("Display method from inner class");
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display(); // 输出:Display method from inner class
}
}
class BaseClass {
void display() {
System.out.println("Display method from base class");
}
}
class DerivedClass extends BaseClass {
@Override
void display() {
System.out.println("Display method from derived class");
}
}
class OuterClass {
class InnerClass extends DerivedClass {
void display() {
System.out.println("Display method from inner class");
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display(); // 输出:Display method from inner class
}
}
这些示例展示了Java内部类的基本用法。您可以根据需要使用内部类来满足您的编程需求。