PDA

View Full Version : How can I calculate Grand total using java polymorphism?


mnhmasum
Apr 25, 2016, 04:17 AM
package javacleancode;


class GrandTotal{
int totalAmount;
int discount;
int deliveryCharge;


void calculateAmount() {
System.out.println("Total " + totalAmount);


}
}


class TotalWithDiscount extends GrandTotal{
void calculateAmount() {
System.out.println("Sub Total " + ((totalAmount - discount)));
}
}


class TotalWithDiscountAndDeliveryCharge extends GrandTotal{
void calculateAmount() {
System.out.println("Grand Total " + ((totalAmount - discount) + deliveryCharge));
}
}






public class JavaCleanCode {

public static void main(String[] args) {

/When no discount and delivery charge available
GrandTotal grandTotal = new GrandTotal();
grandTotal.totalAmount = 450;
grandTotal.calculateAmount();

//When only discount available
GrandTotal totalWithDiscount = new TotalWithDiscount();
totalWithDiscount.discount = 10;
totalWithDiscount.totalAmount = 25;
totalWithDiscount.calculateAmount();

mnhmasum
Apr 25, 2016, 04:19 AM
I am developing an e-commerce application where need to calculate grand total by total price, discount and delivery charge. I want to calculate grand total using polymorphism. Am I going right?


package javacleancode;


class GrandTotal{
int totalAmount;
int discount;
int deliveryCharge;


void calculateAmount() {
System.out.println("Total " + totalAmount);


}
}


class TotalWithDiscount extends GrandTotal{
void calculateAmount() {
System.out.println("Sub Total " + ((totalAmount - discount)));
}
}


class TotalWithDiscountAndDeliveryCharge extends GrandTotal{
void calculateAmount() {
System.out.println("Grand Total " + ((totalAmount - discount) + deliveryCharge));
}
}






public class JavaCleanCode {

public static void main(String[] args) {

/When no discount and delivery charge available
GrandTotal grandTotal = new GrandTotal();
grandTotal.totalAmount = 450;
grandTotal.calculateAmount();

//When only discount available
GrandTotal totalWithDiscount = new TotalWithDiscount();
totalWithDiscount.discount = 10;
totalWithDiscount.totalAmount = 25;
totalWithDiscount.calculateAmount();

//When discount and delivery charge available
GrandTotal totalWithDiscountAndDeliveryCharge = new TotalWithDiscountAndDeliveryCharge();
totalWithDiscountAndDeliveryCharge.deliveryCharge = 100;
totalWithDiscountAndDeliveryCharge.discount = 10;
totalWithDiscountAndDeliveryCharge.totalAmount = 500;
totalWithDiscountAndDeliveryCharge.calculateAmount ();


}

}

CravenMorhead
Apr 25, 2016, 07:22 AM
Yes. That looks right to me.

What is the scope of your assignment?