class Person
{
String name = "no name";
public Person(String nm){name = nm;}
}class Employee extends Person
{
String empID = "0000";
public Employee(String id) { empID=id; }
}class EmployeeTEST
{
public static void main(String [] args)
{
Employee e = new Employee("4321");
System.out.println(e.empID);
}
}
^
1 error
class Person
{
String name = "no name";
public Person(String nm){name = nm;}
}class Employee extends Person
{
String empID = "0000";
public Employee(String id) { super(id); empID=id; } //一看就看出问题了,要么Person有默认构造器,要么像这样自己到调用Person的构造函数,否则没法构造父类对象,又怎么能构造字类对象?
}class EmployeeTEST
{
public static void main(String [] args)
{
Employee e = new Employee("4321");
System.out.println(e.empID);
}
}
2 如果类没有任何构造器,则会有一个无参数的构造器编译时被自动生成,如果有了其他的构造器,则不会自动生成了。所以你的
class Person
书写了一个String参数的构造器,就不能自动生成无参数的构造器了
子类如果不指定 super(String)的构造器,则会因为找不到父类的构造器而报错!
{
String name = "no name";
public Person()----------- 父類構造器改為空
{}
}class Employee extends Person
{
String empID = "0000";
public Employee(String id) { empID=id; }
}class EmployeeTEST
{
public static void main(String [] args)
{
Employee e = new Employee("4321");
System.out.println(e.empID);
}
}
運行結果4321
class Person
{
String name = "no name";
public Person(String nm){name = nm;}
public Person(){} // 这样就可以了
}至于那些名字,都是翻译的问题,叫构造器和构造方法的比较多
String name = "no name";
String empID = "0000";
public Person(String id) {
this.empID = id;
}
}
class Employee extends Person {
public Employee(String id) {
super(id);
}
}
class EmployeeTEST {
public static void main(String[] args) {
Employee e = new Employee("1212");
System.out.println(e.empID);
}
}
這樣也行,直接在父類里面寫方法 子類調用就行了
子類繼承父類是不能有自己的構造方法的
像LS說的那樣 你 new employee的時候他不是用的employee而使用person的構造器
算不算 是对 public Person(String id) { this.empID = id; } 的重写呢?
你new的時候 他調用了父類的構造器 但子類的構造器里一定要有父類的構造器的參數,你可以再加,但父類的參數一定要有,因為集成- -|、
但是{}里面的方法可以不用,自己用自己的(覆蓋率父類構造器里的方法),不寫就用父類的