APLesson_13: Inheritance and Polymorphism

Independent Study

Research the following terms online ...

  • Inheritance
  • super class
  • the extends keyword
  • Polymorphism
  • What does the 'this.' keyword mean?

Take notes on the above terms in your own words. If you need help with any of the concepts, you can ask me.

  1. define each term
  2. Explain how it is used
  3. Give at least 1 example






 


 














APLab_13:

Ex_01: The Toy Inventory System
In this lab, you will be creating an inventory system for different types of toys. You can add a new toy to the system, but adding additional instances of the same toy will add to the number of that kind of toy. You will be able to print out information on these toys and manipulate the data.

The Toy Class
Toy will be an abstract class for different toy objects. It will contain the following instance variables
  • name: holds the name of the toy
  • count: holds how many of that toy in the system

Toy will also contain the following methods
  • Constructors: One default and one with one String parameter. Both set the count equal to 1.
  • Accessors: getName() and getCount()
  • Modifiers: setName() and setCount()
  • Abstract Method: getType()
  • toString(): returns “[Name] [Count]”

The AFigure Class
Extends the Toy class, creates an AFigure (Action Figure) object. Holds all the same methods as Toy, but overrides the getType() method. getType() returns “Action Figure”.

The Car Class
Extends the Toy class, and creates a Car object Holds all the same methods as Toy, but overrides the getType() method. getType() returns “Car”.

The ToyRunner Class
This is to check to make sure that your Toy class is working properly.  You will create a one AFigure, and one Car object, each with a name for a parameter. Use toString() to print information on each object.



The ToyStore Class
Creates a ToyStore object that keeps inventory of all the Toy objects. It contains one instance variable…


  • toyList: An ArrayList of Toy objects

Constructors:
One default and one with a String parameter, which is a list of toys. The constructor runs the loadToys() method below with the input list as a parameter.

The loadToys() Method
Takes in a String which is a list of “toys”, and uses a for loop to check if each toy is in the list.

@param ts
ArrayList of Strings - use ts.split(“, “). Call it “toys”.
For loop from 0 to the size of toys.
String name - toys @ position i
String type - toys @ position i + 1
Create a new Toy object - @ return from getThatToy() @param name
if the return is null
Add new toy - Car if type is “Car”, AFigure if type is “AF”
Otherwise
The toy is already on the list, so set the count to +1.

The getThatToy() Method
Checks toyList by name to see if the toy is in the list.

@param String nm
For each Toy object in toyList
If the name of the toy == nm
Return the Toy object
Return null otherwise

The getMostFrequentToy() Method
Finds the Toy (by name) that occurs most frequently in the list.

New String “name”
New int “max” - Integer.MIN_VALUE
For each Toy object in toyList
If max < the count of the Toy
max = the count of the Toy
name = the name of the Toy
Return the name

The getMostFrequentType() Method
Finds the type of Toy that occurs most frequently in the list.

New int cars - set to 0
New int figures - set to 0

For each Toy in toyList
If the type of Toy is Car
Add one to cars
If the type of Toy is AF
Add one to figures

Return “Cars” if cars is greater than figures
Return “Action Figures” if figures is greater than cars
Return “Equal amounts of action figures and cars!” otherwise

The toString() Method
@ return the toyList






ToyStoreRunner
Write a main that creates a ToyStore object with a String parameter. Print your ToyStore object to make sure it works.


Also, print the output of the getMostFrequentToy() and getMostFrequentType() objects.


Use the following Strings to test...
Hotwheel, Car, G.I.Joe, AF, PennyRacer, Car, Matchbox, Car, Star Wars, AF, Pullback, Car, Star Wars, AF


You should get the following output:


List...
Hotwheel, Car, G.I.Joe, AF, PennyRacer, Car, Matchbox, Car, Star Wars, AF, Pullback, Car, Star Wars, AF
[Hotwheel 1, G.I.Joe 1, PennyRacer 1, Matchbox 1, Star Wars 2, Pullback 1]


Most Frequent Toy: Star Wars
Most Frequent Type of Toy: Cars






In the previous lesson, we created superclasses and and subclasses that extend the superclass. Polymorphism refers to the idea that an object of the subclass can have an “IS - A” relationship with both the subclass and the superclass. As an example, think about the Money objects we made in the previous lesson. Since the Coin and Bill classes are both subclasses of Money, they can be both Money and Coin or Bill objects at the same time.


Coin dime = new Coin();     //IS-A Coin, IS-A Money
Bill one = new Bill();      //IS-A Bill, IS-A Money


This is a perfect example of polymorphism. Because a Coin object “IS-A” Money object, we can even declare the following.
Money change = new Coin(); //perfectly legal


You may be confused by the fact that Money is abstract, and cannot be instantiated. However, remember that all Coin objects are Money objects in the first place, and we instantiated change as a Money object with a type of Coin, which is legal.




Polymorphic Methods
Think about the scan() method we wrote for the Coin class. If you create a Coin object, the scan() method will return the weight of the coin, while a call to scan() on a Bill object will return the face of the bill. This is because both classes inherit scan() from Money, and override the method to create their own specific output.


dime.scan(); //returns the weight of the Coin
one.scan(); //returns the face of the Bill


These two different forms that our scan() method can take is another example of polymorphism.




Reference Variables
As you may already have gathered from the Lesson_12, we can only access objects through reference variables. Below, the variable dime is our reference variable for a Coin object.


Coin dime = new Coin("Dime", 2.268, 00.10);


We access the methods of objects using dot notation.
objectName.methodName(<parameters>);


For example, we can access the methods in our dime object thusly…
dime.scan();


We can also call the toString() by printing a call to the reference variable.
System.out.println(dime); //calls and prints dime’s toString()




Dynamic (Late) Binding vs. Static (early) Binding


Static Binding
Recall in Lesson 12.2 when we used overloaded methods. This is when we have two methods with the same name, but different parameter types. When we run overloaded methods, Java selects the correct version of the method to be used based on the parameters in the call. For example, consider the following 2 calls to the User class from Lab_12.


User pH = new User("Professor", "Handsome");
User pH2 = new User("Professor", "Handsome", "profHansizzle");


Each of the above instantiations uses a different constructor. Java decides which constructor to use at compile-time. This is called early or “static” binding.


Dynamic Binding
Now consider the two different forms of the scan() method in the Money class. Since scan() is overridden in the Coin and Bill classes, when we make the following two calls to scan…


dime.scan(); //returns the weight of the Coin
one.scan(); //returns the face of the Bill


Two different versions of scan() are used in each call. Java decides the version of scan() to use at run time.  This is called late or “dynamic” binding.
 


Testing “IS-A” Relationships
Consider if we added the following subclass of Toy to our project.


public class LightSaber extends Toy
{
  public LightSaber()
  {
      super();
  }


  public LightSaber(String n)
  {
      super(n);
  }


  public String batteries()
  {
      return "4 AAA";
  }


  public String getType()
  {
      return "Lightsaber";
  }
}


In addition to the inherited methods and the overridden getType(), our LightSaber class has the method batteries(), which none of the other subclasses of Toy has, and which is not part of the Toy class.


Therefore, we can make the following program statements.


Toy mine = new LightSaber();
LightSaber yours = new LightSaber();
String w = mine.getName();
String x = yours.getName();


Because both mine and yours are Toy objects (Lightsaber “IS-A” Toy), we can call the getName() method on both. This is because getName() is polymorphic. It is inherited from Toy to LightSaber. However, when we call the batteries() method...


String m = mine.batteries();
String  y = yours.batteries();


An error will be produced, because mine.batteries() does not exist. The batteries() method is not polymorphic, and only exists in LightSaber objects.


In other words, a LightSaber object “IS-A” Toy object, and therefore contains all of the methods of Toy. But  Toy objects are not Lightsabers, and therefore do not contain the batteries() method.




Accessing Variables from the Superclass
We will often need to access the superclass’s instance variable data from the subclass. Keep in mind that although private instance variables are no accessible in the subclass directly. We need to use public methods (accessors) to retrieve the necessary data. As an example, consider the following method that counts the total number of batteries we need for all of the LightSaber objects in our inventory.


public int countBatteries()
{
  return count * 4;
}


This method will produce an error, because count is a private instance variable in Toy, and cannot be accessed directly from a LightSaber object. However, we have a method to get this data. If we rewrite the method using getCount() from the superclass…


public int countBatteries()
{
  return super.getCount() * 4;
}


The method will execute without error, and give use the result that we want. This is why it is important to write accessors for our instance variable data, even when we think we might not need it.




APLab_13.1


Ex_02: Game Systems
This lab creates a hierarchy of Game Systems that covers Different types of consoles and PCs. The class hierarchy is illustrated in the diagram below.
GameSystem Hierarchy


The GameSystem Class
This class contains the following 2 instance variables.
String variable - platform
Int variable - serialNo


Constructors
One default and one that takes in a String parameter “p”
Set Platform = p and serial number to a random 7 digit number


Accessors
One for platform and one for serialNo


The Console Class
This class represents all the console-based game systems. It inherits all instance variables and accessors from GameSystem. Console is abstract and cannot be instantiated.


getController()
An abstract class (String return) to be overridden in the 2 subclasses of Console.


toString()
Returns the following.
Platform: [platform]
Serial #: [serialNo]
Controller: [controller]


Remember that you may need to call accessors on super() to get some of the above data.


XBox
Inherits all the constructors and methods from Console. Overrides getController() to return “XBox Wireless Controller”. Also Overrides getPlatform() to return “XBox”.


PlayStation
Inherits all the constructors and methods from Console. Overrides getController() to return “PS DualShock 3”. Also Overrides getPlatform() to return “PlayStation”.


The PC Class
This class represents all PC-based systems. It inherits all the instance variables and accessors from GameSystem.


systemInput()
Returns “Keyboard and Mouse” and is unique to PC objects.


toString()
Returns the following.
Platform: [platform]
Serial #: [serialNo]
System Input: [device(s)]


Remember that you may need to call accessors on super() to get some of the above data.


GameRunner
Create a variety of GameSystem objects and print them out.






Ex_03: Ticket Sales
In this lab you will be creating a ticket sales program that controls ticket objects and provides both advanced purchase and student discounts.


Ticket Superclass
Creates all ticket objects. This superclass will contain only one instance variable for the serial number (call it “serialNo”). In addition, your superclass will contain the following methods:


  • Constructors: Default constructor only (no @params). Generate a random 7-digit serial number.
  • getSerialNo() - returns a random serial number that is 7 digits.
  • getPrice()- abstract method that returns the price
  • toString() - returns the following (do not include the brackets).
Serial #: [7-digit number]
Price : [price of the ticket]


Advance Class -extends the Ticket class
Private instance variable daysLeft
Constructor takes in a parameter for the number of days left before the event. The Advance class overrides the getPrice() method: if the ticket is purchased 10 or more days prior to the event, the price is 30.00. Otherwise, the price is 40


StudentAdvance Class - extends Advance
Students get half price off tickets. Override getPrice() to divide all ticket prices in half. Override toString() to add “(STUDENT ID REQUIRED)” to the bottom of the String return.


The Walkup Class - extends Ticket
Only overrides getPrice() to produce a standard price of 50.00.


The TicketDriver Class
Create a new class and call it TicketDriver. Use this class to create several Ticket objects and print their information using toString().


Creates 3 ticket objects
  • 1 Walkup
  • 1 Advance
  • 1 Student advance


Print out a receipt using the toString() from each object.








Exam Prep: Test 2


Question_01
Consider the following segment and two classes.


Mambo m = new Mambo();
Rumba r = new Rumba();


public class Rumba
{
  public Rumba()
  {
      System.out.println("Executing the Rumba constructor");
  }
}


public class Mambo
{
  public Mambo()
  {
      System.out.println("executing the Mambo constructor");
  }
}


What is the relationship between class Rumba and class Mambo?


  1. Inheritance only
  2. Composition only
  3. Both inheritance and composition
  4. Polymorphism
  5. There is no class relationship between Rumba and Mambo.







Question_02

Consider the following segment and two classes.

Mambo m = new Mambo();

Rumba r = new Rumba();

public class Rumba

{

  public Rumba()

  {
      System.out.println("Executing the Rumba constructor");
  }
}

public class Mambo extends Rumba

{
  public Mambo()
  {
      /* missing code */
  }
}

The program output is expected to display the following

Executing the Rumba constructor
executing the Mambo constructor
Executing the Rumba constructor


Which of the following can be used to replace the /* missing code */ in constructor Mambo so that the desired output is achieved?

  1. Rumba.super();
System.out.println("executing the Mambo constructor");

  1. System.out.println("executing the Mambo constructor");

  1. super();
System.out.println("executing the Mambo constructor");

  1. I only
  2. II only
  3. III only
  4. I and II
  5. II and III



For questions 03-08, refer to the following CircusPerformer class declaration.


public class CircusPerformer
{
  private String performerName;
  private String actName;


  public CircusPerformer(String pN, String aN)
  {
      performerName = pN;
      actName = aN;
  }
  public String getPerformer()
  {
      return performerName;
  }
  public String getAct()
  {
      return actName;
  }
  public void act()
  {
      entrance();
      performance();
      exit();
  }
  public void entrance()
  {
      System.out.println("Starts in ring center");
  }
  public void performance()
  {
      System.out.println("Runs in circles");
  }
  public void exit()
  {
      System.out.println("Exits from ring center");
  }
}



Question_03


Consider the following code segment and incomplete Equestrian class.


Equestrian sue = new Equestrian("Sue", "Amazing Ponies");
sue.act();


public class Equestrian extends CircusPerformer
{
}


An Equestrian object is a CircusPerformer who rides ponies over the obstacles. Which of the following methods must be defined in the Equestrian class?


  1. CircusPerfomer constructor
  2. act
  3. entrance
  4. performance
  5. exit


  1. I only
  2. II only
  3. III, IV and V
  4. I and II
  5. I and IV

Question_04
An Equestrian is a CircusPerformer who rides ponies over obstacles. Consider the following incomplete Equestrian constructor.


public Equestrian(String aN, String pN)
{
  /* missing code */
}


Which of the following implementations can be used to replace /* missing code */. In constructor Equestrian so that the CircusPerformer instance variables are properly initialized?


  1. super();
performerName = pN;
actName = aN;


  1. super(aN, pN);


  1. super(performerName, actName);


  1. I only
  2. II only
  3. III only
  4. I and II only
  5. I and III only



Question_05
Consider the following code segment and class.


A TightRopWalker is a CircusPerformer who walks and flips on a tightrope.


TightRopeWalker joe = new TightRopeWalker("Joe", "Feats of Daring");
joe.act();


public class TightRopeWalker extends CircusPerformer
{
  public void entrance()
  {
      System.out.println("Starts from tight rope platform");
  }
  public void performance()
  {
      System.out.println("Walks and flips on the tightrope");
  }
  public void exit()
  {
      System.out.println("Exits from tight rope platform");
  }
}


What is printed as a result of executing the code segment?


  1. Starts from tight rope platform
Walks and flips on the tight rope
Exits from tight rope platform


  1. Starts in ring center
Walks and flips on the tight rope
Exits from ring center


  1. Walks and flips on the tight rope


  1. Compile error message indicating that there is a problem with the constructor.


  1. Compile error message indicating that there is a problem with the act method.



Question_06
Consider the following code segment and class.


A TightRopWalker is a CircusPerformer who walks and flips on a tightrope.


TightRopeWalker joe = new TightRopeWalker("Joe", "Feats of Daring");
joe.act();


public class TightRopeWalker extends CircusPerformer
{
  public TightRopeWalker(String pN, String aN)
  {
      super(pN, aN);
  }
  public void entrance()
  {
      System.out.println("Starts from tight rope platform");
  }
  public void performance()
  {
      System.out.println("Walks and flips on the tight rope");
  }
  public void exit()
  {
      System.out.println("Exits from tight rope platform");
  }
}


What is printed as a result of executing the code segment?


  1. Starts from tight rope platform
Walks and flips on the tight rope
Exits from tight rope platform


  1. Starts in ring center
Walks and flips on the tight rope
Exits from ring center


  1. Walks and flips on the tight rope


  1. Compile error message indicating that there is a problem with the constructor.


  1. Compile error message indicating that there is a problem with the act method.





Question_07


Consider the following code segment and class.


HighWireJuggler kathy = new HighWireJuggler("Kathy", "High Wire Juggling");
kathy.act();


public class TightRopeWalker extends CircusPerformer
{
  public TightRopeWalker(String pN, String aN)
  {
      super(pN, aN);
  }
  public void entrance()
  {
      System.out.println("Starts from tight rope platform");
  }
  public void performance()
  {
      System.out.println("Walks and flips on the tight rope");
  }
  public void exit()
  {
      System.out.println("Exits from tight rope platform");
  }
}


public class HighWireJuggler extends TightRopeWalker
{
  public HighWireJuggler(String pN, String aN)
  {
      super(pN, aN);
  }
}


What is printed as a result of executing the code segment?


  1. Starts from tight rope platform
Walks and flips on the tight rope
Exits from tight rope platform


  1. Starts in ring center
Walks and flips on the tight rope
Exits from ring center


  1. Walks and flips on the tight rope


  1. Compile error message indicating that there is a problem with the constructor.


  1. Compile error message indicating that there is a problem with the act method.



Question_08


Consider the following code segment and class.


HighWireJuggler kathy = new HighWireJuggler("Kathy", "High Wire Juggling");
kathy.act();


public class TightRopeWalker extends CircusPerformer
{
  public TightRopeWalker(String pN, String aN)
  {
      super(pN, aN);
  }
  public void entrance()
  {
      System.out.println("Starts from tight rope platform");
  }
  public void performance()
  {
      System.out.println("Walks and flips on the tight rope");
  }
  public void exit()
  {
      System.out.println("Exits from tight rope platform");
  }
}


public class HighWireJuggler extends TightRopeWalker
{
  public HighWireJuggler(String pN, String aN)
  {
      super(pN, aN);
  }


  public void performance()
  {
      System.out.println("Juggles while walking and flipping a tight rope");
  }
}


What is printed as a result of executing the code segment?


  1. Starts from tight rope platform
Walks and flips on the tight rope
Exits from tight rope platform


  1. Starts in ring center
Walks and flips on the tight rope
Exits from ring center


  1. Starts from tight rope platform
Juggles wile walking and flipping a tight rope
Exits from tight rope platform


  1. Compile error message indicating that there is a problem with the constructor.


  1. Compile error message indicating that there is a problem with the act method.



Question_09
Consider the following code segment and two classes


Aardvark andy = new Aardvark();
System.out.println(andy.getAnimalType());


public class Animal
{
  private String animalType;
  public Animal()
  {
      animalType = "Unknown";
  }
  public String getAnimalType()
  {
      return animalType;
  }
}


public class Aardvark extends Animal
{
}


Which of the following are true statements about the Aardvark class?


  1. Aardvark i s a superclass of Animal.
  2. Aardvark will have the exact same features and behaviors as the animal class
  3. Aardvark objects have no access to any methods since the class declaration is empty.


  1. I only
  2. II only
  3. III only
  4. I and II
  5. I and III





Use the following classes for Questions 10 and 11


class Person
{
  public int age;


  public Person()
  {
      System.out.println("Person Constructor");
      age = 17;
  }


  public int getAge()
  {
      return age;
  }
}


public class Student extends Person
{
  public int grade;
  public Student(int g)
  {
      grade = g;
      System.out.println("Student Constructor");
  }
  public int getGrade()
  {
      return grade;
  }
  public void showData()
  {
      System.out.println("Student's Grade is " + grade);
      System.out.println("Student's Age is " + age);
  }
  public static void main(String[]args)
  {
      Student tom = new Student(12);
      Person sue = new Person();
      tom.showData();
  }
}




Question_10
Considering the following code segment…


Student tom = new Student(12);
Person sue = new Person();
tom.showData();


...what are the first 2 lines of output?


  1. Person Constructor
Student Constructor
  1. Student Constructor
Person Constructor


  1. Person Constructor
Person Constructor


  1. Student Constructor
Student Constructor


  1. No Output.
This program do does not compile.




Question_11
Considering the following code segment…


Student tom = new Student(12);
Person sue = new Person();
tom.showData();


...what are the last 2 lines of output?


  1. Student’s Grade is 12
Student’s Age is 17


  1. Student’s Age is 12
Student’s Grade is 17


  1. Student’s Age is 17
Student’s Grade is 12


  1. Student Constructor
Student’s Age is 17


  1. Student Constructor
Student’s Grade is 12




Question_12
Considering the following code segment and two classes.


Person sue = new Person(32);
Student tom = new Student(12, 25);
sue.showData();
tom.showData();


class Person
{
  public int age;


  public Person(int a)
  {
      System.out.println("Person Constructor");
      age = a;
  }


  public int getAge()
  {
      return age;
  }
  public void showData()
  {
      System.out.println("Student's Age is " + age);
  }
}


public class Student extends Person
{
  public int grade;
  public Student(int g, int a)
  {
      super(a);
      grade = g;
      System.out.println("Student Constructor");
  }
  public int getGrade()
  {
      return grade;
  }
  public void showData()
  {
      super.showData();
      System.out.println("Student's Grade is " + grade);
  }
}


What are the last 2 lines of output?


  1. Student’s age is 32
Student’s age is 25
  1. Student’s Age is 25
Student’s Age is 32


  1. Student’s Grade is 12
Student’s Age is 25
  1. Student’s Age is 25
Student’s Grade is 12


  1. No Output.
This program does not compile.




Questions 13 - 22 refer to the Loan, CreditCard, and FinanceCar classes defined below:


public class Loan
{
  private double principal;
  private double interestRate;
  private double total;


  public Loan()
  {
      principal = 0.0;
      interestRate = 0.0;
      total = 0.0;
  }


  public Loan(double p, double rate)
  {
      principal = p;
      interestRate = rate;
      total = p;
  }


  public void payment(double p)
  {  total -= p; }


  public void Fees(double amt) //Add fees to the total
  { /*  implementation not shown  */  }


  public double amountOwed()
  {   return total;   }
}


public class CreditCard extends Loan
{
  public CreditCard()
  {   /* implementation not shown */  }


  public CreditCard(double principal, double rate)
  {   /* implementation not shown */   }
}


public class FinanceCar extends Loan
{
  private static final double GAP = 1000.0;
  private double value;


  public FinanceCar(double p, double rate, double v)
  {  /*  implementation not shown */  }


  /** GAP insurance is added to the total if the loan
   *  total exceeds the value of the car */
  public void needGap()
  {
      /* implementation not shown */
  }
}




Question_13
Of the methods shown, how many different non-constructor methods can be invoked by a FinanceCar object?


  1. 1
  2. 2
  3. 3
  4. 4
  5. 5




Question_14
Which of the following correctly implements the default constructor of the CreditCard class?


  1. super();
principal = 0
interestRate = 0;
total = 0;
  1. super(p, r);
total = p;


  1. super();


  1. II only
  2. I and II only
  3. II and III only
  4. III only
  5. I, II, and III




Question_15
Which is a correct implementation of the constructor with parameters in the FinanceCar class?


  1. principal = p;
interestRate = rate;
value = v;


  1. principal = super.amountOwed();
interestRate = rate;
v = value;


  1. super(p, r);
value = v;


  1. super(p, r, v);
  1. super();
value = v;




Question_16
Which is a correct implementation of the CreditCard constructor?


  1. super();
principal = p;
interestRate = rate;


  1. super(principal, rate);


  1. super(principal, rate);
value = v;


  1. super();


  1. super(principal)
interestRate = rate;



Question_17
Which is the correct implementation of the code for the needGap() method in the FinanceCar class?


  1. super.Fees(GAP);


  1. if(amountOwed() > value)
{
   Fees(GAP);
}


  1. if(super.principal > value)
{
   Fees(GAP);
}


  1. GAP += amount;
if(super.amountOwed() > value)
{
   Fees(GAP);
}


  1. if(super.amountOwed() < value)
{
   super.Fees(GAP);
}




Question_18
Consider the following declarations that will occur in a driver file


Loan l = new Loan(5000, 0.03);
Loan c = new CreditCard(2000, 0.085);
Loan fC = new FinanceCar(20000, 0.059, 25000);


Which method call will cause an error?


  1. c.payment(250);
  2. l.Fees(40);
  3. fC.Fees(GAP);
  4. ((FinanceCar)(fC)).needGap();
  5. c.payment(100);




Question_19
Which of the following from our Loan, CreditCard, and FinanceCar classes is an example of polymorphism?


  1. amountOwed()
  2. payment()
  3. Fees()
  4. The constructors
  5. Any call to super()


Question_20
The constructor in FinanceCar contains a call to super() with the parameters p and rate. When Java decides to use Loan’s constructor with parameters at compile time, this is an example of...


  1. Method overloading
  2. Method overriding
  3. Downcasting
  4. Dynamic binding
  5. Static binding




Question_21
Consider the following declarations and method calls


Loan ln = new Loan(5000, 0.03);
FinanceCar fC = new FinanceCar(20000, 0.059, 25000);


ln.Fees(40);
fC.needGap();


There are 2 calls to Fees() above - one in the Loan object ln and one inside of the needGap() method called in the FinanceCar object fC. Java decides which implementation of the needGap() method to use at run time. This is an example of…


  1. Method overloading
  2. Method overriding
  3. Downcasting
  4. Dynamic binding
  5. Static binding




Question_22
Consider the following declarations.


Loan l = new Loan(5000, 0.03);
Loan c = new CreditCard(2000, 0.085);
FinanceCar fC = new FinanceCar(20000, 0.059, 25000);


Which of the above will cause a ClassCastException?


  1. ((Loan)c).needGap();
  2. ((CreditCard)c).amountOwed();
  3. ((CreditCard)fC).payment(250);
  4. ((Loan)fC).Fees(40);
((FinanceCar)fC).amountOwed();







Question_01
Answer: E
Neither class extends the other so there is no inheritance.
Neither class contains an object of the other class so there is no composition.  Polymorphism requires either inheritance or an interface. Neither is present.


Question_02
Answer: E
Choice I is no good because a constructor is an object method (non-static method). It cannot be called as a class method (static method). Choices II and III both work and do the exact same thing. While choice III explicitly calls the superclass constructor with super, choice II also words because the superclass constructor is automatically called. The super keyword is only necessary when the superclass constructor has parameters.  


Question_03
Answer: E
The term “defined” is confusing in this question. It really means that these methods have to be redefined or overridden in the subclass Equestrian. The Equestrian class would need its own constructor and performance method. Since there is no default constructor for CircusPerfomer objects, subclasses need to pass the performerName and actName data into the constructor in the super. In addition, the description for CircusPerformer says that it “rides ponies over the obstacles”, meaning it does more than just “Runs in circles”. For this reason, we have to override the performance method to print “rides ponies of the obstacles”.


Question_04
Answer: B
I is incorrect, because there is no default constructor for CircusPerformer objects. Therefore, the call to super() in the Equestrian subclass would have to include parameter data. You could get  away with setting values directly on performerName and actName, because they were not declared private in the CircusPerformer superclass. III is incorrect, because you have no variables performerName and actName in the Equestrian constructor.


Question_05
Answer: D
TightRopeWalker does not have a constructor that will send the necessary performerName and actName data to the constructor in the superclass CircusPerformer.


Question_06
Answer: A
The only difference between this and Question_05 is that there is a proper constructor in TightRopeWalker has a proper constructor that passes the necessary information to the superclass.


Question_07
Answer: A
HighWireJuggler neither re-defines nor newly-defines any methods. All methods will be inherited from TightRopeWalker or CircusPerformer. This means that HighWireJuggler objects will behave exactly like TightRopeWalker objects and have the same output.


Question_08
Answer: C
There is only one significant difference between this and Question_07, and that is that HighWireJuggler now re-defines the performance() method. Therefore, all HighWireJuggler objects will enter() and exit() like a TightRopeWalker, but will perform() with “Juggles while walking and flipping a tight rope”.


Question_09
Answer: B
Choice I is wrong because Aardvark is a subclass of Animal, not a superclass. Choice III is wrong because Aardvark will have access to all methods of Animal via inheritance. Choice II is the only correct statement. Since Aardvark is an empty class which inherits from Animal, an Aardvark object will have the same exact behavior as an Animal object. Remember, Aardvark did not re-define or newly-define any methods.


Question_10
Answer: A
The code segment shows the creation of a Student object, followed by the creation of a Person object. Many students would then conclude B would be the answer. What must be remembered is that anytime an object of a subclass is created, the superclass constructor is called first. Consider this: Before you can be enrolled as a student, you must first be born as a person.


Question_11
Answer: A
Here, we know that tom.showData() is the last thing that is called, and that showData() has 2 print statements. Therefore, the last 2 lines of output are going to be the grade and age lines from showData(). We put in a parameter of 12 in the tom object, which gives is a grade of 12, and all Person objects get an age of 17. Therefore, A is the only answer that prints the Grade and Age in order, and has the correct numbers for each.


Question_12
Answer: D
This is similar to 10 and 11. The difference is that The variable age is no longer a set value, but subject to input from the parameter, and is initialized in the Person constructor. Student objects should forward the parameter for age into the constructor for Person.


Question_13
Answer: D
payment(), Fees() and amountOwed() are all inherited from the superclass, plus the needGap() method, which is defined in FinanceCar.


Question_14
Answer: D
You do not have access to the instance variables principal, interestRate, or total in the CreditCard class. Since nothing has changed, you don’t need to write a new default constructor. However, the correct implementation would be just to call the super.


Question_15
Answer: C
The constructor in the superclass Loan asks for principal and interest rate as parameters, so those must be passed in the call to super(). Then, we have the third parameter v, which carries the value of the Car, which we pass into our variable value.


Question_16
Answer: B
For now, CreditCard has the exact same behaviors as the Loan class. The only reason that the constructors are overridden is that they are passing data to the superclass. The constructor in Loan calls for principal and interest rate parameters, which must be passed to the super.


Question_17
Answer: B
In order to add GAP to the total owed, we need to call the Fees() method, which is inherited from the superclass. But first we check to see if the the total amount we owe (variable total in Loan) is greater than value of the car (variable value in FinanceCar). If this is the case, we add the value of GAP to our loan total by calling Fees(GAP).   


Question_18
Answer: C
The calls in A, B, and E are all correct, as they are called in the right place, and contain the correct parameters. C is incorrect, because fC is a Loan object, and does not have access to the variable GAP. D is correct, because fC is first cast to a FinanceCar object, which has access to the needGAP() method.


Question_19
Answer: D
The constructors are overridden, and therefore take on different forms. We learned this in Lesson_12. The payment(), Fees(), and amountOwed() methods share the same implementation in all 3 classes.


Question_20
Answer: E
We learned the difference between static and dynamic binding in Lesson 13.1. Since the constructors are overloaded in Loan, Java will decide which constructor to use at compile time based on the parameters used.


Question_21
Answer: D
We learned the difference between static and dynamic binding in Lesson 13.1. Since the implementation of the Fees() method is the same in each class and not overridden, Java must decide at runtime which implementation to use.


Question_22
Answer: C

Since fC is a FinanceCar object and not a CreditCard object, you cannot cast an object to a type of an unrelated class. All of the other casts are valid.