Skip to content

Instantly share code, notes, and snippets.

@bhnascar
Created March 25, 2017 21:12
Show Gist options
  • Save bhnascar/a0a729114477c2632b7cd14c50299deb to your computer and use it in GitHub Desktop.
Save bhnascar/a0a729114477c2632b7cd14c50299deb to your computer and use it in GitHub Desktop.
Inheritance practice questions
class InheritancePractice
{
public static abstract class Vehicle
{
public int maxSpeed; // In MPH
public int acceleration; // In 0-60MPH secs
public Vehicle(int maxSpeed, int acceleration) {
this.maxSpeed = maxSpeed;
this.acceleration = acceleration;
if (maxSpeed > 100) {
System.out.println("Woah, fast car dude!!");
}
else {
System.out.println("What a dud, man.");
}
}
}
public static class Car extends Vehicle
{
private String manufacturer;
public Car(String manufacturer) {
super(150, 10);
}
}
public static class SovietKV1Tank extends Vehicle
{
public int ammo; // How much ammo.
public SovietKV1Tank(int ammo) {
this.ammo = ammo;
System.out.println("These still exist?!");
}
public void FireFlakGun() {
if (ammo > 0) {
ammo--;
System.out.println("BOOOOOMMMMMMMM!");
}
}
}
public static void main(String[] args) {
System.out.println("Warmup exercises!");
}
}
/*
1. True or false: This doesn't compile because an abstract class must have
at least one abstract method.
2. What gets printed when the following constructor is called?
Car car = new Car();
(A) Nothing is printed.
(B) Woah, fast car dude!
(C) What a dud, man.
(D)
(E) This code doesn't compile.
3. What gets printed when the following constructor is called?
SovietKV1Tank tank = new SovietKV1Tank(500);
(A) What a dud, man.
(B) These still exist?
(C) What a dud, man. These still exist?
(D) Nothing is printed.
(E) This code doesn't compile.
4. Given the following code:
Vehicle ferrari = new Car("Ferrari");
Vehicle russianTank = new SovietKV1Tank();
Which of the following statements will *not* cause an error?
(A) System.out.println(tank.ammo);
(B) tank.FireFlakGun();
(C) System.out.println(ferrari.manufacturer);
(D) double topSpeed = ferrari.maxSpeed;
(E) All of the above will cause an error.
5. Which of the following casts (and assignments) are legal?
(A) Vehicle v = (Car)ferrari;
(B) Car v = (Car)russianTank;
(C) Car v = (Car)ferrari;
(D) Both A and C.
(E) None of the above.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment