user3114967
user3114967

Reputation: 629

How to return new instance with preset fields from a constructor

XHTML:

<p:carousel value="#{carouselView.cars}" var="car" itemStyleClass="carItem">
    <h:panelGrid columns="2" style="width:100%" cellpadding="5" columnClasses="label,value">
        <f:facet name="header">
            <p:graphicImage name="../images/cars/#{car.brand}.gif"/> 
        </f:facet>

        <h:outputText value="Id:" />
        <h:outputText value="#{car.id}" />

        <h:outputText value="Year" />
        <h:outputText value="#{car.year}" />

        <h:outputText value="Color:" />
        <h:outputText value="#{car.color}" style="color:#{car.color}"/>

Package1 have 1 java file:
CarService.java

public class CarService {

    private final static String[] colors;

    private final static String[] brands;

    static {
        colors = new String[10];
        colors[0] = "Black";
        colors[1] = "White";
        colors[2] = "Green";
        colors[3] = "Red";

        brands = new String[10];
        brands[0] = "BMW";
        brands[1] = "Mercedes";
        brands[2] = "Volvo";
        brands[3] = "Audi";
     }
     public List<Car> createCars(int size) {
        List<Car> list = new ArrayList<Car>();
            list.add(new Car(getRandomId(), getRandomBrand(), getRandomYear());

        return list;
    }

    private String getRandomId() {
        return UUID.randomUUID().toString().substring(0, 8);
    }

    private int getRandomYear() {
        return (int) (Math.random() * 50 + 1960);
    }

    private String getRandomBrand() {
        return brands[(int) (Math.random() * 10)];
    }


    public List<String> getColors() {
        return Arrays.asList(colors);
    }

    public List<String> getBrands() {
        return Arrays.asList(brands);
    }
}

Package2 have 2 java file:
1.CarouselView.java

public class CarouselView implements Serializable {
    private List<Car> cars;
    private Car selectedCar;
    private CarService service;
    @PostConstruct
    public void init() {
        cars = service.createCars(3);
    }

    public List<Car> getCars() {
        return cars;
    }

    public void setService(CarService service) {
        this.service = service;
    }

    public Car getSelectedCar() {
        return selectedCar;
    }

    public void setSelectedCar(Car selectedCar) {
        this.selectedCar = selectedCar;
    }
}

2.Car.java

public class Car {

    String randomId;
    String randomBrand;
    int randomYear;
    public Car(String randomId, String randomBrand, int randomYear) {
        this.randomId = randomId;
        this.randomBrand = randomBrand;
        this.randomYear = randomYear;
    }
}

I'm getting error like,

Caused by: java.lang.NullPointerException at com.abc.mmc.dto.CarouselView.init(CarouselView.java:35)

Upvotes: 0

Views: 217

Answers (5)

CubeJockey
CubeJockey

Reputation: 2219

A constructor shouldn't return anything. For typical POJO's (Pretty Ordinary Java Objects) the goal is to just create (or construct) your object with the specified arguments.

For example:

public class Car {
    private String randomId;
    private String randomBrand;
    private String randomYear;

    public Car(String randomId, String randomBrand, int randomYear) {
        this.randomId = randomId; 
        this.randomBrand = randomBrand;
        this.randomYear = randomYear;
    } 

    //Getters and Setters follow
}

this.randomId = randomId; You take the argument randomId and assign it to the Class variable this.randomId

This is common convention. Here is an alternate code fragment to elaborate on intent (though the prior is preferred, assuming your variables are named well):

private String carId;
private String carBrand;
private int carYear;

public Car(String randomId, String randomBrand, int randomYear){
   carId = randomId;
   carBrand = randomBrand;
   carYear = randomYear;
}

If you're passing arguments to a method's constructor and not doing anything with them, it's a waste of time. You're just building naked Objects. It is important to take the incoming parameters and 'design' your Car object with those items.


Edit following OP update:

You're getting a NullPointerException on your service.createCars(3); because you aren't initializing your CarService object:

private Car selectedCar;
private CarService service;
@PostConstruct
public void init() {
    service = new CarService(); //Create your service object
    cars = service.createCars(3);
}

Upvotes: 1

Razib
Razib

Reputation: 11163

Constructor can never have a return type even can not have a return type void and the constructor name must be similar with the class name. But constructor may be private or public-

private Car(); //or
public Car();  

From you problem description it seems you need to add some getter/setter method to give access your private field in Car class.

To work correctly with constructor you don't need to add return statement from it. Any class which create a Car instance/object can use the new operator along with the public constructor -

//In some class that need an instance/object
//of Car class
Car aCar = new Car(... //arguments list);

Note: Here the Car() is public constructor and it has no return type. In the above statement following things are occurred -
1. JVM create a new instance/object with the public constructor Car()
2. The newly created object of type Car is assigned with the Car type reference variable - aCar.

Upvotes: 1

AlexG
AlexG

Reputation: 31

In such a simple constructor, I would not return any value at all. With more complexity, relying on external sources especially, I might add a boolean for if construction succeeded or failed.

Upvotes: 0

Gaurav Jeswani
Gaurav Jeswani

Reputation: 4582

You need not to return anything. Constructor has no return. It's has the use of initialization.

Upvotes: 0

Sandeep Kaul
Sandeep Kaul

Reputation: 3267

Constructor does not return anything. You might want to set some values in the constructor from the arguments into the object. Something like:

public class Car {
    private String randomId;
    private String randomBrand;
    private int randomYear;
    public Car(String randomId, String randomBrand, int randomYear) {
        this.randomId = randomId;
        this.randomBrand = randomBrand;
        this.randomYear = randomYear;
    }
}

Upvotes: 1

Related Questions