简体   繁体   中英

Java:Creating an Object from Class

We are just getting into objects and I came across an issue. Given the following class I created...

public class employee{
    String name;
    int waiting_time;
    int retaining_time;

    public employee(String name)
    {
        this.name=name;
    }

    public void setWaitingTime(int waitingtime)
    {
        waiting_time = waitingtime;
    }

    public int getWaitingTime()
    {
        return waiting_time;
    }

    public void setRetainingTime(int retainingtime)
    {
        retaining_time = retainingtime;
    }

    public int getRetainingTime()
    {
        return retaining_time;
    }
}

I'm trying to write a function that creates an instance of this class, and then sets waiting_time and retaining_time to 0 for only the first time it's created. Those two values will be added/subtracted upon later in the program, but they must be 0 at the start.

public static void addEmployee(String aName)
{
    employee anEmployee = new employee();  //error here says library.employee() is undefined?
}

I've done it exactly how they've done it in our book, not sure where I'm going wrong. Thanks for the help!

If you add this constructor

public employee(String name)
{
    this.name=name;
}

there is no default constructor without parameters. A default constructor is only generated for you if you do not write any constructors yourself. If you want a constructor with no parameters in addition to this other one, you have to add it

public employee() { }

By the way, classes in Java normally begin with a capital letter.

Add following constructor in your class

public employee()
{
    this.waiting_time=0;
    this.retaining_time=0;
}

The error is due to the absence of default constructor as you have added another constructor. Since you wanted to set waiting_time and retaining_time to 0; so I have just done the same in this constructor

Your only constructor for the class requires a String as an argument. You need to pass the string as an argument:

employee anEmployee = new employee(aName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM