Java JDK 8 assignment (CarbonFootprint Interface: Polymorphism) Using interfaces
ID: 3698969 • Letter: J
Question
Java JDK 8 assignment
(CarbonFootprint Interface: Polymorphism) Using interfaces, you can specify similar
behaviors for possibly disparate classes. Governments and companies worldwide are
becoming increasingly concerned with carbon footprints (annual releases of carbon dioxide
into the atmosphere) from buildings burning various types of fuels for heat, vehicles
burning fuels for power, and the like. Many scientists blame these greenhouse gases for the
phenomenon called global warming. Create three small classes unrelated by inheritance—
classes Building, Car and Bicycle. Write an interface CarbonFootprint with a
getCarbonFootprint method. Have each of your classes implement that interface, so that its
getCarbonFootprint method prints out an appropriate message (e.g., this message from
Building CarbonFoot).Write an application that creates objects of each of the three classes
and one interface reference variable, assign each object to the interface reference variable,
and then invoke each object’s getCarbonFootprint method by means of dynamic method
resolution. For each object, print a simple message (e.g., this message from Building
CarbonFoot).
Explanation / Answer
/* This is the interface CarbonFootprint */
interface CarbonFootprint
{
public void getCarbonFootprint(); /* abstract method of the interface*/
}
class Building implements CarbonFootprint /*Building class implementing the interface CarbonFootprint*/
{
public void getCarbonFootprint() /*Implementation of getCarbonFootprint menthod in Building class */
{
System.out.println("This msg from Building CarbonFoot");
}
}
class Car implements CarbonFootprint
{
public void getCarbonFootprint()/*Implementation of getCarbonFootprint menthod in Car class */
{
System.out.println("This msg from Car CarbonFoot");
}
}
class Bicycle implements CarbonFootprint
{
public void getCarbonFootprint()/*Implementation of getCarbonFootprint menthod in Bicycle class */
{
System.out.println("This msg from Bicycle CarbonFoot");
}
}
public class Demo1
{
public static void main(String args[])
{
CarbonFootprint r1; /* reference variable of CarbonFootprint interface */
r1 = new Building(); /* refernce variable of the CarbonFootprint interface referring to Building class object */
r1.getCarbonFootprint();
r1= new Car();/*refernce variable of the CarbonFootprint interface referring to Car class object */
r1.getCarbonFootprint();
r1= new Bicycle();/*refernce variable of the CarbonFootprint interface referring to Bicycle class object */
r1.getCarbonFootprint();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.