DEV Community

Sasireka
Sasireka

Posted on

Constructor Program in Java

public class Supermart {

    String productName;
    int price;
    boolean discountAvailable;
    int discountPercentage;

    public Supermart(String productName, int price, boolean discountAvailable, int discountPercentage) {

        this.productName = productName;
        this.price = price;
        this.discountAvailable = discountAvailable;
        this.discountPercentage = discountPercentage;
    }

    public static void main(String[] args) {

        Supermart p1 = new Supermart("Rice",1000,true,20);

        p1.display();
    }

    public void display() {

        int finalPrice = price;

        if(discountAvailable) {
            finalPrice = price - (price * discountPercentage / 100);
        }

        System.out.println("Product Name: " + productName);
        System.out.println("Price: " + price);
        System.out.println("Discount Available: " + discountAvailable);

        if(discountAvailable) {
            System.out.println("Discount Percentage: " + discountPercentage);
        }

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

}
Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)