【问题标题】:Error in Java Test ClassJava 测试类中的错误
【发布时间】:2013-06-17 11:02:42
【问题描述】:

这是我有错误的测试类,我无法弄清楚它到底是什么。

import java.util.*;
public class EmployeeTest 
{

public static void main(String[] args) {
    Employee e = new Employee();
    e.setId("100012");
    e.setLastname("Smith"); 
    ResponsibilityDecorator d;
    d = new Recruiter(e);
    d = new CommunityLiaison(e);
    d = new ProductionDesigner(e);      
    System.out.println(e.toString());
}
}

这是链接到测试类的类

public class Employee 
{

String id;
String lastname;

Employee(String id, String lastname) 

{

    this.id=id;
    this.lastname=lastname;

}
 EmploymentDuties eduties=new EmploymentDuties();

public EmploymentDuties getDuties()
{
    return eduties;
}
public String toString(){
    return "Duties for this employee: "+eduties.jobtitles;
}

public void setId(String id)
{
    this.id = id;
}

public void setLastname(String lastname)
{
    this.lastname = lastname;
}


}

【问题讨论】:

  • 你怎么知道你有错误?!堆栈跟踪?还是你的 ide 在做标记?
  • 给我们一个线索:你看到的错误是什么?

标签: java decorator


【解决方案1】:

Employee 中没有 no-args 构造函数。添加参数以使用EmployeeTest中已有的构造函数

Employee e = new Employee("100012", "Smith");

陈述

e.setId("100012");
e.setLastname("Smith");

然后是多余的,可以删除。

【讨论】:

  • 如上所示提供预期的参数。这样做后实际上不需要调用setIdsetLastname :)
  • 不错的一个。如果一切都解决了,别忘了accept an answer :)
【解决方案2】:

您的 Employee 类只定义了一个构造函数:Employee(String, String)。确保从 EmployeeTest 调用它或定义无参数构造函数。

【讨论】:

    【解决方案3】:

    默认构造函数是java提供的构造函数,没有你提供的构造函数。

    一旦您提供了任何构造函数,就不再提供默认构造函数。

    你创建了构造函数

    Employee(String id, String lastname) 
    
    {
    

    并像使用一样

    Employee e = new Employee();  //not possible
    

    【讨论】:

    • @user2478522 查看 Reimus 的回答,使用它。
    • java.lang.UnsupportedClassVersionError: EmployeeTest : Unsupported major.minor version 51.0 找不到主类:EmployeeTest。程序将会退出。线程“main”Java 结果中的异常:1
    【解决方案4】:

    默认构造函数是自动生成的无参数构造函数除非你定义了另一个构造函数。

    这是默认构造函数:

     Employee() {}
    

    然后你可以实例化像这样的对象:

    Employee e = new Employee();
    

    如果显式定义了至少一个构造函数,则不会生成默认构造函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 2015-04-25
      相关资源
      最近更新 更多