Task 10a - Interfaces in Java - Java Programming Practice Exercise

Due to ever increasing use of fossil fuels (petrol, diesel, etc.) in our daily lives, the amount of greenhouse gases i.e. Carbon Dioxide (CO2) in the atmosphere is rapidly increasing, which is causing global warming. Scientists have associated values called “Carbon Footprint” to almost all human activities. For example each square feet of a covered area generates about 0.005 tons of CO2 annually. A car generates 0.0000292 tons of CO2 for each mile it is driven.

In order to handle the “Carbon Footprint”, your job is to create an interface called CarbonFootPrintProducer that shall contain a method declaration called getCarbonFootPrint(), that shall return a double value indicating the amount of CO2 generated by an instance of the implementing class.

Your next job is to create two classes i.e. House and Car, both shall implement CarbonFootPrintProducer interface. House must have an attribute coveredArea, while Car must have an attribute milesDriven, both public. Create fully parametrized constructor in each subclass. Both subclasses must contain their own getCarbonFootPrint() implementation that shall calculate the CO2. For the calculation of CO2, use the following formulas.

CO2 produced by House = coveredArea * 0.005
CO2 produced by a Car = milesDriven *  0.0000292

Create a class CarbonFootPrintTest. Define static method calculateTotalFootPrint(ArrayList <CarbonFootPrintProducer> entities) method that shall calculate and return total CO2 of passed collection using polymorphism. Also define the main method in test class that shall create one object of House and Car passing user given coveredArea and milesDriven, respectively, to the constructor. Add both objects in an ArrayList and print total CO2 generated by House and Car using calculateTotalFootPrint method.

Sample runs of the program is given below.

Enter miles by a Car: 100
Enter Covered Area of a House: 1000
The total Carbon Foot Print is 5.002920 tone(s) of CO2