1、创建汽车接口
public interface Car {
void start();
void run();
void stop();
}
2、创建司机类
public class Driver {
class Benz implements Car {
private String model;
private double price;
private String color;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public void speak() {
System.out.println(color + "色奔驰[" + model + "]单价:" + price + "万~");
}
@Override
public void start() {
System.out.println("奔驰[" + model + "]起步……");
}
@Override
public void run() {
System.out.println("奔驰[" + model + "]行驶……");
}
@Override
public void stop() {
System.out.println("奔驰[" + model + "]停止……");
}
}
}
3、创建测试司机类
public class TestDriver {
public static void main(String[] args) {
// 创建司机对象(外部类对象)
Driver driver = new Driver();
// 设置司机对象属性
driver.setName("唐小刚");
// 基于司机对象(外部类对象)创建奔驰对象(内部类对象)
Driver.Benz benz = driver.new Benz();
// 设置奔驰对象属性
benz.setModel("梅赛德斯-AMG A 35 L 4MATIC");
benz.setPrice(45);
benz.setColor("蓝");
// 调用司机对象的驾驶方法
driver.drive(benz);
}
}
5、修改测试司机类类,演示匿名内部类
public class TestDriver {
public static void main(String[] args) {
// 创建司机对象(外部类对象)
Driver driver = new Driver();
// 设置司机对象属性
driver.setName("唐小刚");
Driver.Benz benz = driver.new Benz();
// 设置奔驰对象属性
benz.setModel("梅赛德斯-AMG A 35 L 4MATIC");
benz.setPrice(45);
benz.setColor("蓝");
driver.drive(benz);
System.out.println("=======================");
driver.drive(new Car() {
private String model = "全新BMW Z4敞篷跑车";
private double price = 55;
private String color = "红";
@Override
public void start() {
System.out.println("宝马[" + model + "]起步……");
}
@Override
public void run() {
System.out.println("宝马[" + model + "]行驶……");
}
@Override
public void stop() {
System.out.println("宝马[" + model + "]停止……");
}
public void speak() {
System.out.println(color + "色宝马[" + model + "]单价:" + price + "万~");
}
});
}
}
6.运行程序查看结果