Polymorphic billing

Polymorphic billing

Medium Java OOP Basics 17 views
Explanation Complexity

Problem Statement

Task: create interface Billable and two implementations. Return total bill for array of Billable.

Input Format

An array of Billable objects

Output Format

Total bill amount (sum of all items)

Example

Item1 bill = 100
Item2 bill = 200
300

Constraints

• Must use interface

• At least two different implementations

• Total is sum of all bills

Concept Explanation

Billable interface defines a method like getBill().
Two different classes implement it (for example Product and Service).
We store them in a Billable array.
We call getBill() on each and add them.

Step-by-Step Explanation

1.Create interface Billable with method to return bill amount.

2.Create two classes implementing Billable.

3.Each class calculates its bill in its own way.

4.Create an array of Billable.

5.Initialize total = 0.

6.Loop through array:

• Call bill method for each object.

• Add result to total.

7.Return total.

Concept Explanation

Billable interface defines a method like getBill().
Two different classes implement it (for example Product and Service).
We store them in a Billable array.
We call getBill() on each and add them.

Step-by-Step Explanation

1.Create interface Billable with method to return bill amount.

2.Create two classes implementing Billable.

3.Each class calculates its bill in its own way.

4.Create an array of Billable.

5.Initialize total = 0.

6.Loop through array:

• Call bill method for each object.

• Add result to total.

7.Return total.

Input / Output Format

Input Format
An array of Billable objects
Output Format
Total bill amount (sum of all items)
Constraints
• Must use interface

• At least two different implementations

• Total is sum of all bills

Examples

Input:
Item1 bill = 100 Item2 bill = 200
Output:
300

Example Solution (Public)

Java
static interface Billable{int bill();}static class Item implements Billable{final int price;Item(int p){price=p;}public int bill(){return price;}}static class Pack implements Billable{final int unit;final int qty;Pack(int u,int q){unit=u;qty=q;}public int bill(){return unit*qty;}}static int total(Billable[] a){int s=0;for(Billable b:a) s+=b.bill();return s;}

Official Solution Code

static interface Billable{int bill();}static class Item implements Billable{final int price;Item(int p){price=p;}public int bill(){return price;}}static class Pack implements Billable{final int unit;final int qty;Pack(int u,int q){unit=u;qty=q;}public int bill(){return unit*qty;}}static int total(Billable[] a){int s=0;for(Billable b:a) s+=b.bill();return s;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.