有时它会创建错误,因为没有构造函数,有时还可以

时间:2019-11-18 10:49:43

标签: java constructor

为什么此代码无法使用“ Apple需要构造函数”进行编译?

class Fruit {
  public Fruit(String name) {
    System.out.println("Fruit's constructor is invoked");
  }
}

public class Apple extends Fruit {}

这段代码有一个没有构造函数的类(GraduateStudent),可以吗?

public class Demo{
  public static void main(String[] args) {
    m(new GraduateStudent());
    m(new Student());
    m(new Person());
    m(new Object());
  }

  public static void m(Object x) {
    System.out.println(x.toString());
  }
}

class GraduateStudent extends Student {
}

class Student extends Person {
  public String toString() {
    return "Student";
  }
}

class Person extends Object {
  public String toString() {
    return "Person";
  }
}

0 个答案:

没有答案