DEV Community

S Sarumathi
S Sarumathi

Posted on

Constructor Program In Java

public class Shopp {
    String Name;
    int price;
    boolean discountavail;
    int discountper;

    public Shopp(String Name, int price, boolean discountavail, int discountper) {
        this.Name = Name;
        this.price = price;
        this.discountavail = discountavail;
        this.discountper = discountper;
    }

    public static void main(String[] args) {
        Shopp P1 = new Shop("Chocolate", 150, false, 0);
        Shopp P2 = new Shop("Rice", 150, true, 20);
        Shopp P3 = new Shop("Oil", 150, true, 15);
        Shopp P4 = new Shop("Ghee", 150, false, 0);

        P1.buy();
        P2.buy();
        P3.buy();
        P4.buy();
    }

    public boolean discount() {
        return discountavail;
    }

    public int finalPrice() {
        if (discount()) {
            return price - (price * discountper / 100);
        } else {
            return price;
        }
    }

    public void buy() {
        System.out.println("Name: " + Name);
        System.out.println("Price: " + price);
        System.out.println("Discount Available: " + discountavail);
        System.out.println("Discount Percentage: " + discountper);

        if (discount()) {
            System.out.println("Discount Applied: " + discountper + "%");
        }

        System.out.println("Final Price: " + finalPrice());

    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)