- 下面这段代码的输出结果是什么?
public class Test {
public static void main(String[] args) {
new Circle();
}
}
class Draw {
public Draw(String type) {
System.out.println(type+" draw constructor");
}
}
class Shape {
private Draw draw = new Draw("shape");
public Shape(){
System.out.println("shape constructor");
}
}
class Circle extends Shape {
private Draw draw = new Draw("circle");
public Circle() {
System.out.println("circle constructor");
}
}
运行结果
shape draw constructor
shape constructor
circle draw constructor
circle constructor
父类的构造器调用以及初始化过程一定在子类的前面。
由于Circle类的父类是Shape类,所以Shape类先进行初始化,然后再执行Shape类的构造器。接着才是对子类Circle进行初始化,最后执行Circle的构造器。
2.下面这段代码的输出结果是什么?
public class Test {
public static void main(String[] args) {
Shape shape = new Circle();
System.out.println(shape.name);
shape.printType();
shape.printName();
}
}
class Shape {
public String name = "shape";
public Shape(){
System.out.println("shape constructor");
}
public void printType() {
System.out.println("this is shape");
}
public static void printName() {
System.out.println("shape");
}
}
class Circle extends Shape {
public String name = "circle";
public Circle() {