在Java中调用测试类中的创建类

时间:2015-04-25 18:18:53

标签: java

我创建了一个公共类: Employee 。现在我想创建一个驱动类来测试这个新类。但是,我无法弄清楚如何在驱动程序类中调用我创建的类: EmployeeTest 。我已将每个类( Employee EmployeeTest )放在同一目录中;但是,我仍然收到错误消息:"找不到类员工。"

任何人都可以帮助我走上正轨吗?

以下是我的员工的代码:

 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);

 }

1 个答案:

答案 0 :(得分:1)

根据您的代码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; 
 }
相关问题