Quiz J3-1
Submit your answers via this Google Form
Question 1
Consider the classes below:
interface WallOutlet {
// Frequency is different from country to country
public double getFrequency();
public double getPower();
}
interface Battery {
public double getSize();
public double getPower();
}
class Electricity implements Battery {
public int amp_hours =0;
public boolean alternating_current=false;
public double voltage =0.0;
public double getSize() {
return amp_hours;
}
public double getPower() {
return amp_hours * voltage;
}
}
class PowerPlant extends Electricity implements WallOutlet {
public PowerPlant() {
super();
this.amp_hours = 100;
this.alternating_current = true;
this.voltage = 120.0;
}
public double getFrequency() {
return 240;
}
public double getPower() {
//Half since it's AC
return super.getPower() /2;
}
}
Someone who works at the Seabrook Station Nuclear Plant decided they want to use
it as a battery to charge their phone! What’s the output of the program below?
public class Main {
public static void main(final String args[]) {
PowerPlant seabrook_station = new PowerPlant();
System.out.println("Power level: "+((Battery)seabrook_station).getPower());
}
}
Question 2
Say we add the class below to our power program:
class AABattery extends Electricity implements Battery{
public double getPower() {
// AA Batteries are weak :/
return 1.0;
}
public double getSize() {
return super.getSize();
}
}
Now in the program below someone tries to convert a AA battery to a power plant,
what’s the output?
public static void main(final String args[]) {
AABattery remote_battery = new AABattery();
PowerPlant personal_power_plant = (PowerPlant)((Battery) remote_battery);
System.out.println("Power level: "+personal_power_plant.getFrequency());
}
Question 3
What if someone does the opposite, and tries to turn a Power Plant into a AA
battery?
public static void main(final String args[]) {
PowerPlant power_plant = new PowerPlant();
AABattery personal_power_plant = (AABattery)((Battery) power_plant);
System.out.println("Power level: "+personal_power_plant.getPower());
}
Question 4
Finally someone added a converter from AA Batteries to Power Plants. What’s the output of the below program?
public static PowerPlant powerPlantCreator(Electricity e){
if(e instanceof PowerPlant)
return (PowerPlant)e;
else if(e instanceof AABattery){
PowerPlant p = new PowerPlant();
p.alternating_current = true;
p.amp_hours = e.amp_hours;
// Power plants output way higher voltages
p.voltage = e.voltage * 100;
return p;
}
return null;
}
public static void main(final String args[]) {
AABattery remote_battery = new AABattery();
PowerPlant personal_power_plant = powerPlantCreator(remote_battery);
System.out.println("Power level: "+personal_power_plant.getPower());
}