![]() ![]() |
|
继承内部类的构造器问题 | |
作者:佚名 文章来源:不详 点击数 更新时间:2008/10/22 21:35:30 文章录入:杜斌 责任编辑:杜斌 | |
|
|
class Car { class Wheel { } } class PlaneWheel extends Car.Wheel { PlaneWheel(Car car) { car.super(); // 这句什么意思?为什么要这样写? } public static void main(String[] args) { Car car = new Car(); PlaneWheel pw = new PlaneWheel(car); } } 调用的是 Car.Wheel 的构造器 因为 你这个类,是集成自 Car.Wheel而不是 Car. 同样,因为你不是单纯的集成子Wheel,所以你必须有一个Car的实例,因为Wheel属于Car。 以下的几种情况都是错误的 class Car { class Wheel { Wheel(int id) { // 不再有默认无参数构造器 } } } class PlaneWheel extends Car.Wheel { PlaneWheel(Car car) { car.super(); // 这里会出现编译错误 } public static void main(String[] args) { Car car = new Car(); PlaneWheel pw = new PlaneWheel(car); } } 不写调用 class Car { class Wheel { } } class PlaneWheel extends Car.Wheel { PlaneWheel(Car car) { // 不写调用,也会出现编译错误 } public static void main(String[] args) { Car car = new Car(); PlaneWheel pw = new PlaneWheel(car); } } class Car { class Wheel { } } class PlaneWheel extends Car.Wheel { PlaneWheel(Car car) { super();// 单纯的super,同样是错误的 } public static void main(String[] args) { Car car = new Car(); PlaneWheel pw = new PlaneWheel(car); } } |
|
![]() ![]() |