Adv Java Skill 5
Adv Java Skill 5
QUESTION :
A company named XYZ Retail is in the business of selling Books, CDs and Cosmetics. Books are sales
tax exempt, CDs and Cosmetics have a sales tax of 10%. CDs can be imported and attracts an import
tax of 5%. Write a simple shopping basket program, which will calculate extended price (qty *
(unitprice + tax)) inclusive of tax for each item in the basket?
CODE :
package com.patterns.gof;
//abstract by default
double getExtendedTax();
double getExtendedTaxedPrice();
String getDescription();
import java.math.BigDecimal;
// define attributes
this.description = description;
this.qty = qty;
this.price = price;
return extTax.doubleValue();
}
public double getExtendedTaxedPrice() {
if (tax == null) {
BigDecimal extPrice =
BigDecimal.valueOf(qty).multiply(calculatedTax.add(price));
return extPrice.doubleValue();
return description;
package com.patterns.gof;
import java.math.BigDecimal;
public interface TaxCalculator {
abstract BigDecimal getCalculatedTax(boolean isTaxable, boolean
isImported, BigDecimal price);
}
package com.patterns.gof;
import java.math.BigDecimal;
public class TaxCalculatorImpl implements TaxCalculator {
// Stay away from hard coding values. Read from a “.properties”
file
public static final BigDecimal SALES_TAX =
BigDecimal.valueOf(0.10); // 10%
public static final BigDecimal IMPORT_TAX =
BigDecimal.valueOf(0.05); // 5%
public BigDecimal getCalculatedTax(boolean isTaxable, boolean
isImported, BigDecimal price) {
if(price == null){
throw new IllegalArgumentException("Price cannot be null");
}
BigDecimal salesTax = BigDecimal.ZERO;
BigDecimal importTax = BigDecimal.ZER0
if (isTaxable) {
salesTax = price.multiply(SALES_TAX);
}
if (isImported) {
importTax = price.multiply(IMPORT_TAX);
}
return salesTax.add(importTax);
}
}
STEP-4: Now, the specific Goods like Book, CD, and Cosmetics that
extends the shared behavior. In other words, inherits the shared
behavior of Goods. The isTaxable & isImportedare specific to the
product. New products can be added in the future with specific
taxable & importable behaviors.
package com.patterns.gof;
import java.math.BigDecimal;
public class Book extends Goods {
//default values
private boolean isTaxed = false;
private boolean isImported = false;
public Book(String description, int qty, BigDecimal price) {
super(description, qty, price);
}
}
OUTPUT:
VIVA:
1) What are interfaces in java and how they are implemented in
java?