Just like this :
class Car {
int carId;
String brand;
public Car(int carId, String brand) {
this.carId = carId;
this.brand = brand;
}
// getter and setter
public String toString() {
return " car :" + "id - " + carId + ", brand - " + brand;
}
}
public class User {
String name;
Car car;
// getter and setter
public String toString() {
return name + " has a " + car.toString();
}
public static void main(String[] args) {
// 1st
User u = new User() {
{ // my problem is here : is this block OK?
setName("Tom");
setCar(new Car(1, "Volvo"));
}
};
// 2nd or this
// Car car = new Car(1, "Volvo");
// User u = new User();
// u.setName("Tom");
// u.setCar(car);
System.out.println(u);
}
}
I know this works fine in C#, and it seems that it also works in Java. However, it's really not clear that if that's right or a good code style... Really thanks for your help!