如何从参数化构造函数(Java)中调用构造函数?

时间:2016-08-04 14:21:43

标签: java constructor

我正在使用构造函数来理解它,我遇到了一个问题。这是代码。如果代码太长,可以使用。

import java.util.Scanner;

class Employee {

    int id,sal;
    String name;
    String desig;

    Employee()
    {
        id=001;
        name="Paul";
        desig="VirtualWorker";
        sal=10000;
    }

    Employee(int def, String message)
    {
        System.out.println("How to fill in details(Example):");
        System.out.println("ID:"+id);
        System.out.println("Name:"+name);
        System.out.println("Designation:"+desig);
        System.out.println("Salary:"+sal);
        System.out.println("Default value:"+def);
        System.out.println("Default message:"+message);
    }

    void input()
    {
        Scanner in=new Scanner(System.in);
        System.out.println("");
        System.out.println("Welcome to SS Enterprises!");
        System.out.println("What is the id?");
        id=in.nextInt();
        System.out.println("What's the name of employee?");
        name=in.next();
        System.out.println("What's the designation?");
        desig=in.next();
        System.out.println("What's the salary?");
        sal=in.nextInt();
    }

    void print()
    {
        System.out.println("");
        System.out.println("ID:"+id);
        System.out.println("Name:"+name);
        System.out.println("Designation:"+desig);
        System.out.println("Salary:"+sal);
    }

    public static void main(String args[])
    {
        Employee emp=new Employee();
        Employee emp2=new Employee(929,"Message in constructor.");
        Employee emp3=new Employee();
        emp3.input();
        emp3.print();
    }       
}

当在输出中打印参数化构造函数的值时,我不会获得默认构造函数中给出的值。我得到默认值,如0或null。

有什么方法可以获取默认构造函数的值并在参数化构造函数中使用它?

提前致谢

2 个答案:

答案 0 :(得分:0)

您可以这样称呼它们:

Employee(){
    // This calls the other constructor with the default values
    this(defaultDef, defaultMessage); 
    // The rest of the default constructor 
}

Employee(int def, String message){
    // The rest of the parameterised constructor
}

答案 1 :(得分:0)

您可以从内部显式调用默认构造函数:

<强> EDITED

Employee(int def, String message)
{
    this();
    ...