3

我正在尝试创建一个无参数构造函数,它将从用户(通过 Scanner 类)获取所有实例变量的输入,但它是从另一个类继承的。

我该怎么做呢?

这是我所做的:

 public class Manager extends Super_Employee{
     String  manager ;

     /* String GetManger  (){
         return manager ;
     }*/

     Manager (){
        Scanner manager = new Scanner(System.in);
     }

     @Override
     String Print() {
         return ("the manager is : " +manager);
     }

这是超级类:

 public  class Super_Employee extends abstract_Employee {

     String Fname ;
     String Lname;
     String address;
     int number;
     Super_Employee(String Fname,String Lname, String address, int number)
    {
        System.out.println("Constructing an Employee");
        this.Fname = Fname ;
        this.Lname = Lname;
        this.address = address;
        this.number = number;
    }  


 @Override
    String Print (){
    return ("the employee name is : "+Fname+ " "+ Lname+ " ,the Employee address is  : "
            + address + " ,the employee Phone # : "+number);   
} 
}
4

4 回答 4

2

当您需要在子类中定义一个不会调用超类中的非默认构造函数的默认构造函数时,您必须在子类中提供一个默认构造函数。令人困惑?看看这个例子。

public class Foo {
    public Foo( String x ) {
    }
}

public class Bar extends Foo {
    public Bar() {
        super(); // this is called implicitly even if this line is not provided! compilation error here
    } 
}

在上面的示例中,子类构造函数将调用子类的默认构造函数 super(),因此您必须在超类中提供默认构造函数或这样编写子类:

public class Bar extends Foo {
    public Bar() {
        super( "hadoken!" ); // now it works, since it calls a constructor that exists
    } 
}

现在,如果您没有在 Foo 类中提供任何构造函数,它将有一个默认构造函数(由编译器提供)。

于 2012-08-17T03:35:59.070 回答
2

在中添加一个无参数构造函数Super_Employee

Super_Employee() { }

既然,你有

Super_Employee(String Fname,String Lname, String address, int number) {
    //...

编译器不提供默认构造函数(这是构造函数本身提供的无参数构造函数)。

于 2012-08-17T03:37:15.897 回答
2

根据您的错误,听起来您的超类需要 3 个参数,但您正在尝试使用默认构造函数,因为您还没有这三个值的值。在这种情况下,我建议使用工厂方法来构造您的对象。

例子:

public class Manager extends Super_Employee{

    /** Factory method, reading constructor arguments from System.in */
    public static Manager make() {
        Scanner s = new Scanner(System.in);
        new Manager(s.next(), s.next(), s.next(), s.nextInt());
    }

    public Manager(String fName, String lName, String address, int number) {
        super(fName, lName, address, number);
    }

     // . . .

使用工厂方法Manager.make()构造您的对象允许您在调用超级构造函数之前读取您需要的所有值System.in,这在构造函数中是不可能的Manager

于 2012-08-17T03:37:38.947 回答
2

一些可能的选项:

1)使用静态构建器

public static Manager newManager() {

 .....

return new Manager(.....);

2)创建无参数超级构造函数:

Super_Employee() {
   ...
}}

3)可以使用“二等舱” - 相当丑陋,我不建议

public Manager() {
  this(new MyTemp());
}

public Manager(MyTemp temp) {
  super(temp.fname, temp.lname,....);
}
于 2012-08-17T03:46:55.180 回答