0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

assert method

Posted at

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)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?