一、内部类
1. 基本介绍
- 将一个类的定义放在另一个类的内部
- 把一些逻辑相关的类组织在一起,并控制内部类的可见性
- 内部类了解外部类,并能与之通信
- 用内部类写出的代码,更加优雅而清晰
2. 普通内部类
package com.day.dreamer.queue;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
public class Table {
private String color;
private String brand;
private Fruit food;
public void addFruit() {
Fruit fruit = new Fruit("apple");
food = fruit;
}
public Fruit getFruit() {
return food;
}
@AllArgsConstructor
@Data
class Fruit {
private String name;
public void sayName() {
System.out.println("my name is:" + name);
}
public void getAccess() {
System.out.println(color);
System.out.println(brand);
}
public Table getTable() {
return Table.this;
}
}
}
package com.day.dreamer.queue;
public class Demo07 {
public static void main(String[] args) {
Table table = new Table();
table.setColor("Red");
table.setBrand("Italy");
table.addFruit();
Table.Fruit fruit = table.getFruit();
System.out.println(fruit.getName());
Table second = new Table();
Table.Fruit peach = second.new Fruit("peach");
System.out.println(peach);
}
}