assertを、入力値チェック、出力値チェック、コンストラクタチェックなどに使う
assertはデフォルト無効なため、java -eaオプションで実行すること
class Item{
private String name;
private int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
assert price > 100 : "constructor price over error";
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
assert price > 100 : "set price over error";
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Order{
Item item;
int amount;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public Order(Item item, int amount) {
this.item = item;
this.amount = amount;
}
int calc() {
return this.item.getPrice() * this.amount;
}
}
public class Outer {
public static void main(String args[]) {
Item i = null;
i = new Item("apple",50);
i.setPrice(150);
int amount = 30;
Order o = new Order(i,amount);
int oPrice = o.calc();
assert oPrice == i.getPrice() * amount: "calc price error";
}
}
C:\Users\***\Documents\NetBeansProjects\mavenproject1\target\classes>java -ea com.mycompany.mavenproject1.Outer
Exception in thread "main" java.lang.AssertionError: constructor price over error
at com.mycompany.mavenproject1.Item.<init>(Outer.java:15)
at com.mycompany.mavenproject1.Outer.main(Outer.java:66)