New Object Initialization in Java - Coffee example (
Page 3 of 4 )
For example, if you wanted to create a virtual coffee cup, and then fill it with virtual coffee, your code would look like this:
// In Source Packet in ex2/CoffeeCup.java
// Approach 1
class CoffeeCup {
private int innerCoffee = 355;
// no constructors defined in this version of CoffeeCup
//...
Or an acceptable alternative version of the code to initialize your object could look like this:
// In Source Packet in ex5/CoffeeCup.java
// Approach 3
class CoffeeCup {
private int innerCoffee;
// Only two constructors defined in this
// version of CoffeeCup
public CoffeeCup() {
}
public CoffeeCup(int startingAmount) {
if (startingAmount < 0) {
String s = "Can't have negative coffee.";
throw new IllegalArgumentException(s);
}
innerCoffee = startingAmount;
}
//...
}
}