CODE
class IceCreamPricesWithOverriding
{
public static void main(String arg[])
{
IceCream ic = new IceCream();
ic.flavor = "Pista";
ic.numberOfScoops = 2;
System.out.println(ic.numberOfScoops + " scoops of " + ic.flavor + " flavor price is : " + ic.getPrice());
FruitSaladWithIceCream fs = new FruitSaladWithIceCream();
fs.flavor = "Chocolate";
fs.numberOfScoops = 1;
fs.gramsOfFruitSalad = 50;
System.out.print(fs.gramsOfFruitSalad + " grams of fruit salad and ");
System.out.println(fs.numberOfScoops + " scoops of " + fs.flavor + " flavor price is : " + fs.getPrice());
KhubaniKaMeetaWithIceCream kkm = new KhubaniKaMeetaWithIceCream();
kkm.flavor = "Vanila";
kkm.numberOfScoops = 1;
kkm.gramsOfKhubaniKaMeeta = 75;
System.out.print(kkm.gramsOfKhubaniKaMeeta + " grams of khubani ka meeta and ");
System.out.println(kkm.numberOfScoops + " scoops of " + kkm.flavor + " flavor price is : " + kkm.getPrice());
}
}
class IceCream
{
String flavor;
int numberOfScoops;
double getPrice()
{
double pricePerScoop = 35.0;
return numberOfScoops * pricePerScoop;
}
}
class FruitSaladWithIceCream extends IceCream
{
int gramsOfFruitSalad;
double getPrice()
{
double iceCreamPrice = super.getPrice(); // LINE A
double pricePerGram = 0.75;
return gramsOfFruitSalad * pricePerGram + iceCreamPrice;
}
}
class KhubaniKaMeetaWithIceCream extends IceCream
{
int gramsOfKhubaniKaMeeta;
double getPrice()
{
double iceCreamPrice = super.getPrice(); // LINE B
double pricePerGram = 1.25;
return gramsOfKhubaniKaMeeta * pricePerGram + iceCreamPrice;
}
}
2 scoops of Pista flavor price is : 70.0
50 grams of fruit salad and 1 scoops of Chocolate flavor price is : 72.5
75 grams of khubani ka meeta and 1 scoops of Vanila flavor price is : 128.75
In this program similar to Inheritance Example Program To Remove Duplicate Code we have created 3 classes - IceCream
, FruitSaladWithIceCream
and FruitSaladWithIceCream
. But the name of the method which gives the price is same for all of them. The method is called getPrice
. This program also uses the super
keyword to distinguish between the getPrice
method of the sub-class and the super-class.
BadamMilkWithIceCream
which extends from IceCream
and add member variable milliLitersOfBadamMilk
and add a method getPrice
which calls super.getPrice()
to get the price of the ice cream. Assume that the price of milli liter of badam milk is Rs. 0.20.