创建Java类的新对象将返回一个null对象

时间:2011-12-19 18:42:29

标签: java class

我已经创建了一个新类'ServiceRequest',如下所示。我没有在这里添加getter和setter以节省空间。

package testListenerPackage;

import java.util.Date;

public class ServiceRequest {

public static final ServiceRequest REQUEST_ARRIVAL   = new ServiceRequest( "Request_Arrival" );
public static final ServiceRequest REQUEST_COMPLETION   = new ServiceRequest( "Request_Completion" );
public static final ServiceRequest REQUEST_UNDER_PROCESS = new ServiceRequest( "Request_Under_Process" );


private String serviceRequest;
private String requestName;
private int requestID;
private long arrivalTime;
private long startServiceTime;
private long endServiceTime;
private long totalServiceTime;

private String requestStatus;

public enum RequestStatus{
    NEW, COMPLETED
}



public ServiceRequest()
{

}
public ServiceRequest( String serviceRequest ) {
    serviceRequest = serviceRequest;
 }
}

当我尝试在其他类中创建此对象的实例时,它会返回一个null对象。

  public ServiceRequest generateServiceRequest()
{
    ServiceRequest serviceRequest = new ServiceRequest("Ali baba");
    serviceRequest.setRequestID(1);
    serviceRequest.setRequestName("Read");
    serviceRequest.setRequestStatus(ServiceRequest.REQUEST_ARRIVAL.toString());
    serviceRequest.setArrivalTime(System.currentTimeMillis());
    return serviceRequest;
}

有人可以告诉我该怎么做吗?

2 个答案:

答案 0 :(得分:1)

我不喜欢这段代码:

public ServiceRequest()
{
    // all those references are null - crazy
}
public ServiceRequest(String serviceRequest ) {
    // use "this" to clarify what's initialized
    this.serviceRequest = serviceRequest;
}

答案 1 :(得分:0)

当他的意思是“空对象”时,他的意思是该对象中没有任何东西(他的serviceRequest字符串)。正如Beau Grantham所说,“这个”将完成工作