How can I calculate Grand total using java polymorphism?
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();
Am I going right to calculate grand total using java polymorphism?
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 ();
}
}