我创建了一个公共类:雇员。现在,我想创建一个驱动器类来测试这个新类。但是,我不知道如何在驱动程序类EmployeeTest中调用我创建的类。我已经将每个类(Employee和EmployeeTest)放置在同一目录中。但是,我仍然收到错误消息:“找不到班级雇员”。

谁能帮助我走上正确的路?

这是我的Employee类代码:

 package employee;

  /**
  *
  * @author ljferris
  */
 public class Employee {

    private String first; // Instance variable for first name
    private String last; // Instance variable for last name
    public double salary; // Instance variable for monthly salary

 // Constructor initializes first with parameter firstName and intializes last with parameter lastName
 public Employee(String firstName, String lastName){
     this.first = firstName;
     this.last = lastName;
 }

 // Constructor initializes salary with parameter monthlySalary
 public Employee(double monthlySalary){
     this.salary = monthlySalary;
 }

 // Method to set the first and last name
 public void setName(String firstName, String lastName){
     this.first = firstName;
     this.last = lastName;
 }

 // Method to set the  monthly salary
 public void setSalary (double monthlySalary){
     this.salary = monthlySalary;

     if (salary > 0.0)
         this.salary = monthlySalary;
 }

 // Method to retrive the first and last name
 public String getName(){
     return first + last;
 }

  // Method to retrive monthly Salary
  public double getSalary (){
     return salary;
 }

 } // End class Employee


这是EmployeeTest的代码:

 package employeetest;

 /**
  *
  * @author ljferris
  */

 import java.util.Scanner;

 public class EmployeeTest {

     public static void main(String[] args) {

     Employee employee1 = new Employee("Leviticus Ferris", 1200.00);

 }

最佳答案

根据您的代码,EmployeeEmployeeTest位于不同的程序包中。您需要在import employee类中添加EmployeeTest。然后,您可以从new Employee创建EmployeeTest实例。

package employeetest;

import employee;
import java.util.Scanner;

public class EmployeeTest {

 public static void main(String[] args) {

 Employee employee1 = new Employee("Leviticus Ferris", 1200.00);

}


更新以下评论:

使用firstNamesalary作为参数添加一个构造函数。

 public Employee(String firstName, double salary){
    this.first = firstName;
    this.salary = salary;
 }


如果要初始化3个值。通过使用所有字段,再添加一个构造函数。

 public Employee(String firstName, String lastName, double salary){
    this.first = firstName;
    this.last = lastName;
    this.salary = salary;
 }

关于java - 在Java的测试类中调用创建的类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29868921/

10-10 14:23