0% found this document useful (0 votes)
4 views35 pages

Combine PDF

The document contains a series of multiple-choice questions related to object-oriented programming concepts, specifically focusing on inheritance in Java. It includes questions about class definitions, constructors, method overriding, and polymorphism, with examples involving classes like Book, TextBook, BankAccount, SavingsAccount, and CheckingAccount. The questions assess understanding of how inheritance works, method implementations, and the behavior of objects in different contexts.

Uploaded by

dcoolcal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views35 pages

Combine PDF

The document contains a series of multiple-choice questions related to object-oriented programming concepts, specifically focusing on inheritance in Java. It includes questions about class definitions, constructors, method overriding, and polymorphism, with examples involving classes like Book, TextBook, BankAccount, SavingsAccount, and CheckingAccount. The questions assess understanding of how inheritance works, method implementations, and the behavior of objects in different contexts.

Uploaded by

dcoolcal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Unit 9: Inheritance​ ​ ​ ​ ​ ​ ​ ​ ​ Name: _________________

Unit 9 Summative Review III - MCQ Practice

C 1) Consider the following class definitions.

public class Book


{
private String bookTitle;

public Book()
{
bookTitle = "";
}

public Book(String title)


{
bookTitle = title;
}
}

public class TextBook extends Book


{
private String subject;

public TextBook(String theSubject)


{
subject = theSubject;
}
}

The following code segment appears in a method in a class other than Book or TextBook.

Book b = new TextBook("Geometry");

Which of the following best describes the effect of executing the code segment?

(A) The TextBook constructor initializes the instance variable subject with the value of "Geometry", and
then calls the default Book constructor, which initializes the instance variable bookTitle to "".

(B) The TextBook constructor initializes the instance variable subject with the value of "Geometry", and
then invokes the one-parameter Book constructor, which initializes the instance variable bookTitle to
"Geometry".

(C) There is an implicit call to the default Book constructor first, and the instance variable bookTitle is then
initialized to "". Then, the instance variable subject is initialized with the value of "Geometry".

(D) There is an implicit call to the default Book constructor first, and the instance variable bookTitle is then
initialized to "Geometry". Then, the instance variable subject is initialized with the value of "Geometry".

(E) The code segment will not execute because the TextBook constructor does not contain an explicit call to
one of the Book constructors.
The next two questions refer to the two classes defined below:

public class ThisClass public class ThatClass extends ThisClass


{ {
​ public ThisClass() ​ public ThatClass()
​ { ​ {
​ ​ System.out.print("better "); ​ ​ System.out.print("make it ");
​ } ​ }

​ public void speak() ​ public void speak()


​ { ​ {
​ ​ System.out.print("do it "); ​ System.out.print("faster ");
​ } ​ }
} }

B 2) What is printed when the following line of code is executed?

ThisClass example = new ThatClass();

(A) Nothing is printed, Java will not let us initialize an object declared as a different type.
(B) better make it
(C) make it
(D) make it better
(E) better

A 3) If example is declared as in the previous question:

ThisClass example = new ThatClass();

What is printed when the following call is made?

example.speak();

(A) faster
(B) do it
(C) do it faster
(D) faster do it
(E) Nothing is printed. speak is a ThisClass method and example is a ThatClass object
Use the following classes to answer the questions that follow.

public class exampleA { public class exampleB extends exampleA {


​ private int number; ​ private int otherNumber;

​ public exampleA(int n) { ​ public exampleB(int first, double second) {


​ ​ number = n; ​ ​ /*implementation asked for in 4*/
} ​ }

public int getNumber(){ ​ public void toString() {


​ return number; ​ ​ /*implementation asked for in 5*/
} ​ }

public void setNumber(int n) { public boolean equals(example ex) {


​ number = n; /*implementation asked for in 6*/
} }
} }

B 4) Which of the following is a correct way to implement the parameter constructor in exampleB?

I. setNumber(first); II. super(first); III. this.setNumber(first)


otherNumber = second; otherNumber = second; ;
otherNumber = second;

(A) I only
(B) I and II only
(C) II and III only
(D) I and III only
(E) I, II, and III

D 5) Which of the following is the correct way to implement the toString() method in exampleB so that
it returns its two instance variables?

(A) return first + getNumber();


(B) return otherNumber + this.number;
(C) return first + " " + second;
(D) return otherNumber + " " + getNumber();
(E) return otherNumber + getNumber();

B 6) Which of the following is a correct way to implement the equals method in exampleA so that it returns
true if both exampleB objects have the same data and false otherwise?

I. return this.otherNumber == ex.otherNumber && this.getNumber() ==


ex.getNumber();

II. if(otherNumber == ex.otherNumber && getNumber() == ex.getNumber())


​ return true;
else
​ return false;

III. return otherNumber == ex.otherNumber && this.number == ex.number;


(A) I only​ (B) I and II only​ (C) II and III only​ (D) I and III only​ (E) I, II, and III
C
C 7) Consider the following class definition.

public class WhatsIt


{
​ private int length;
​ private int width;

​ public WhatsIt()
{
​ ​ //implementation not shown
​ }

​ public WhatsIt(int l, int w)


{
​ ​ //implementation not shown
​ }

​ public int getArea ()


{
​​ // implementation not shown
​ }

​ private int getPerimeter ()


{
​​ // implementation not shown
​ }
}

A child class AmaCallIt that extends WhatsIt would inherit:

(A) length, width, WhatsIt(), WhatsIt(int l, int w), getArea(), getPerimeter()


(B) length, width, WhatsIt(), WhatsIt(int l, int w), getArea()
(C) WhatsIt(), WhatsIt(int l, int w), getArea()
(D) length, width, getArea(), getPerimeter()
(E) length, width, getArea()
Use the following classes to answer questions 8-10:

public class Athlete {


​ private String name;

​ public Athlete() {
​ ​ name = "Athlete 1";
​ }

​ public void play() {


​ ​ System.out.print("athlete play ");
​ ​ run();
​ }

​ public void run() {


​ ​ System.out.print("athlete run ");
​ }

​ public String getName() { return name; }


}

public class TrackStar extends Athlete {


​ private double mile;

​ public TrackStar() {
​ ​ super();
​ ​ mile = 8.5;
​ }

​ public void play() {


​ ​ System.out.print("track play ");
​ ​ super.run();
​ }

​ public void run() {


​ ​ System.out.print("track run ");
​ }

​ public double getMile() { return mile; }


}

B 8) The following instantiation appears in a class other than Athlete or TrackStar:

Athlete micah = new TrackStar();

What is printed as a result of micah.play()?

(A) athlete play athlete run


(B) track play athlete run
(C) athlete play track run
(D) track play track run
(E) Error, an Athlete cannot be instantiated as a TrackStar
C 9) You want to add an equals method to TrackStar to compare two TrackStar objects. Which of the
following has the correct implementation of that equals method?

I. public boolean equals(TrackStar obj)


{
return getName() == obj.getName() && getMile() == obj.getMile();
}

II. public boolean equals(Athlete obj)


{
return getName().equals(((TrackStar) obj).getName()) &&
getMile() == ((TrackStar) obj).getMile();
}

III. public boolean equals(Object obj)


{
return getName().equals(((TrackStar) obj).getName()) &&
this.mile == ((TrackStar) obj).mile;
}

(A) I only
(B) I and II only
(C) II and III only
(D) I and III only
(E) I, II, and III

A 10) An array of TrackStars are created:

Athlete[] roster = new Athlete[2];


roster[0] = new TrackStar();
roster[1] = new Athlete();

Which of the following correctly prints track play athlete run?

(A) roster[0].play();
(B) roster[0].run();
(C) roster[1].play();
(D) roster[1].run();
(E) roster[0].play();
roster[1].run();
Unit 9: Inheritance​ ​ ​ ​ ​ ​ ​ ​ Name: ________________________
Unit 9 Summative Review II​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​

Multiple Choice

Questions 1−10 refer to the BankAccount, SavingsAccount, and CheckingAccount classes defined
below:

public class BankAccount


{
​ private double balance;

​ public BankAccount()
​ { balance = 0; }

​ public BankAccount(double acctBalance)
​ { balance = acctBalance; }

​ public void deposit(double amount)


​ { balance += amount; }

​ public void withdraw(double amount)


​ { balance -= amount; }

​ public double getBalance()


​ { return balance; }
}

public class SavingsAccount extends BankAccount


{
private double interestRate;

public SavingsAccount()
{ /* implementation not shown */ }

public SavingsAccount(double acctBalance, double rate)


{ /* implementation not shown */ }

public void addInterest() //add interest to balance


{ /* implementation not shown */ }
}
public class CheckingAccount extends BankAccount
{
private static final double FEE = 2.0;
private static final double MIN_BALANCE = 50.0;

public CheckingAccount(double acctBalance)


{ /*implementation now shown */}

/**Fee of $2 deducted if withdraw leaves balance less than


*MIN_BALANCE. Allows for negative balance */
public void withdraw(double amount)
{ /*implementation not shown*/}
}

D 1) Of the methods shown, how many different non-constructor methods can be invoked by a
SavingsAccount object?

(A) 1​ ​
(B) 2​ ​
(C) 3​ ​
(D) 4​ ​
(E) 5

A 2) Which of the following correctly implements the default constructor of the SavingsAccount class?

I.​ interestRate = 0;
​ super();

II.​ super();
​ interestRate = 0;

III.​ super(interestRate);

(A) II only
(B) I and II only
(C) II and III only
(D) III only
(E) I, II, and III
D 3) Which is a correct implementation of the constructor with parameters in the SavingsAccount class?

(A)​ balance = acctBalance;


​ interestRate = rate;

(B)​ getBalance() = acctBalance;


​ interestRate = rate;

(C) ​ super();
​ interestRate = rate;

(D) ​ super(acctBalance);
​ interestRate = rate;

(E)​ super(acctBalance, rate);

E 4) Which is a correct implementation of the CheckingAccount constructor?

I.​ super(acctBalance);​ ​ ​
​ ​ ​ ​ ​ ​ ​
II.​ super();​ ​ ​ ​ ​
​ deposit(acctBalance);​ ​ ​
​ ​ ​ ​ ​ ​ ​
III.​ deposit(acctBalance);

(A) I only
(B) II only
(C) III only
(D) II and III only
(E) I, II, and III

C 5) Which is the correct implementation code for the withdraw method in the CheckingAccount class?

(A)​ super.withdraw(amount);
​ if(balance < MIN_BALANCE)
​ ​ super.withdraw(FEE);

(B)​ withdraw(amount);
​ if(balance < MIN_BALANCE)
​ ​ withdraw(FEE);
(C)​ super.withdraw(amount);
​ if(getBalance() < MIN_BALANCE)
​ ​ super.withdraw(FEE);

(D) ​ withdraw(amount);
​ if(getBalance() < MIN_BALANCE)
​ ​ withdraw(FEE);

(E)​ balance -= amount;


​ if(balance < MIN_BALANCE)
​ ​ balance -= FEE;

B 6) Redefining the withdraw method in the CheckingAccount class is an example of

(A) method overloading


(B) method overriding
(C) downcasting
(D) dynamic binding (late binding)
(E) static binding (early binding)

Use the following for Questions 7−9:

A program to test the BankAccount, SavingsAccount, and CheckingAccount classes has these
declarations:

BankAccount b = new BankAccount(1400);


BankAccount s = new SavingsAccount(1000, 0.04);
BankAccount c = new CheckingAccount(500);

E 7) Which method call will cause an error?

(A) b.deposit(200);​ ​
(B) s.withdraw(500);
(C) c.withdraw(500);​ ​
(D) s.deposit(10000);
(E) s.addInterest();

D 8) In order to test polymorphism, which method must be used in the program?


(A) Either a SavingsAccount constructor or a CheckingAccount constructor
(B) addInterest
(C) deposit
(D) withdraw
(E) getBalance

C 9) Which of the following will not cause a ClassCastException to be thrown?

(A) ((SavingsAccount) b).addinterest();


(B) ((CheckingAccount) b).withdraw(200);
(C) ((CheckingAccount) c).deposit(800);
(D) ((CheckingAccount) s).withdraw(150);
(E) ((SavingsAccount) c).addInterest();

A 10) A new method is added to the BankAccount class.

/** Transfer amount from this BankAccount to another BankAccount


* Precondition: balance > amount
*/
public void transfer(BankAccount another, double amount){
​ withdraw(amount);
​ another.deposit(amount);
}

A program has these declarations:

BankAccount b = new BankAccount(650);


SavingsAccount DisneySavings = new SavingsAccount(1500, 0.03);
CheckingAccount GoldieChecking = new CheckingAccount(2000);

Which of the following will transfer money from one account to another without error?

I. b.transfer(DisneySavings, 50);
II. DisneySavings.transfer(GoldieChecking, 30);
III. GoldieChecking.transfer(b, 55);

(A) I only
(B) II only
(C) III only
(D) I, II, and III
(E) None

A 11) What two methods from Object are often overridden?


(A) toString, equals
(B) toString, add
(C) add, remove
(D) add, compareTo
(E) toString, compareTo

Questions 12−14 refer to the following:

public class A {
​ public A() {
​​ System.out.print("pear ");
​ }

public A(int z) {
​​ System.out.print("peach ");
​ }

​ public void doStuff(){


​​ System.out.print("banana ");
​ }
}

public class B extends A {


​ public B() {
​​ super ();
​​ System.out.print("apple ");
}

​ public B(int val) {


​​ super(val);
​​ System.out.print("kiwi ");
​ }
}

A 12) What is printed when the following line of code is executed?

B fruit = new B();

(A) pear apple


(B) peach apple
(C) peach kiwi
(D) apple pear
(E) apple kiwi

E 13) What is printed when the following line of code is executed?


A otherFruit = new B(5);

(A) kiwi peach


(B) pear kiwi
(C) pear peach kiwi
(D) peach apple kiwi
(E) peach kiwi

C 14) What is printed when the following line of code is executed?

B otherFruit = new B(5);


otherFruit.doStuff();

(A) pear kiwi banana


(B) kiwi banana
(C) peach kiwi banana
(D) banana
(E) Nothing is printed; doStuff() cannot run since otherFruit was created as a B object.

A 15) Which of the following is true about the immediate parent and child classes of a class?

(A) Every class can have many different child classes but only one parent class
(B) Every class can have many different child classes and many different parent classes
(C) Every class can have either one parent class or one child class, not both
(D) Every class can have only one child class but many different parent classes
(E) Every class can have only one child class and only one parent class

Free Response
16) A class Triangle has been created. It has three instance data, Point p1, p2, p3, a constructor that
receives the 3 Points and initializes p1, p2, and p3, a toString method that outputs the 3 Points, and a
computeSurfaceArea method that calculates the surface area of the Triangle (as a double value).

We want to extend this class to represent a 3-dimensional Pyramid, which consists of 4 Points. Since the
Pyramid will consist of 4 triangles, the computeSurfaceArea method for the Pyramid will compute the
surface area of the Triangle made up of 3 of those 4 Points.

Write the Pyramid class to handle the difference(s) between a Pyramid and the previously defined
Triangle. Assume that the class Point has a toString method.

public class Pyramid extends Triangle {


private Point p4;

public Pyramid(Point p1, Point p2, Point p3, Point p4) {


super(p1, p2, p3);
this.p4 = p4;
}

public double computeSurfaceArea() {


double baseArea = super.computeSurfaceArea();
double side1 = new Triangle(p1, p2, p4).computeSurfaceArea();
double side2 = new Triangle(p2, p3, p4).computeSurfaceArea();
double side3 = new Triangle(p3, p1, p4).computeSurfaceArea();
return baseArea + side1 + side2 + side3;
}

public String toString() {


return super.toString() + " Fourth Point: " + p4.toString();
}
}
Unit 9: Inheritance​ ​ ​ ​ ​ ​ ​ ​ Name: ______________________
Unit 9 Summative Review I

Use the following class to answer the questions that follow.

public class Person


{
private int myAge;

public Person(){
myAge = 0;
}
public Person(int x){
myAge = x;
}

public void setAge(int age){


myAge = age;
}

public int getAge(){


return myAge;
}

public void haveBirthday(){


myAge++;
}

public void saySomething(){


System.out.println("I am a person");
}
}

1) Write an Employee class that is-a Person.

Employee should have the following:


●​ two instance variables: salary and vacationDays
●​ A default constructor with an explicit call to the Person’s default constructor.
●​ A two-parameter constructor with an explicit call to Person’s default constructor.
●​ A three-parameter constructor with an explicit call to Person’s parameter constructor.
●​ A polymorphic method called saySomething()
public class Employee extends Person {
private double salary;
private int vacationDays;

public Employee() {
super();
salary = 0.0;
vacationDays = 0;
}

public Employee(double salary, int vacationDays) {


super();
this.salary = salary;
this.vacationDays = vacationDays;
}

public Employee(int age, double salary, int vacationDays) {


super(age);
this.salary = salary;
this.vacationDays = vacationDays;
}

public void saySomething() {


System.out.println("I am an employee");
}
}

2) Draw an inheritance hierarchy chart for Person, Student, Employee, and APStudent in the space to
the left. Then, circle Legal or Illegal next to each line of code, identifying if the upcasting or aliasing is allowed.

Person Person z = new Employee(); Legal / Illegal


/ \
Student Employee APStudent y = new Employee(); Legal / Illegal
|
Student x = new Employee(); Legal / Illegal
APStudent
Student w = new APStudent(); Legal / Illegal
Person v = new Student();
Person u = new Employee();
v = u; Legal / Illegal
Person t = new Person();
Employee s = new Employee();
t = s; Legal / Illegal
Person r = new Student();
Student q = new Student();
q = r; Legal / Illegal

3) Write the toString() and equals() method for an Employee. Format the String nicely, but it can be
done however you would like.

public class Employee extends Person {


private double salary;
private int vacationDays;

public String toString() {


return "Employee: Age = " + getAge() + ", Salary = " + salary + ", Vacation Days = " + vacationDays;
}

public boolean equals(Object obj) {


if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Employee other = (Employee) obj;
return this.getAge() == other.getAge() &&
this.salary == other.salary &&
this.vacationDays == other.vacationDays;
}
}
4) Consider the following code:

Person A = new Person();


Person B = new Employee();
Person C = new Student();
Person D = new APStudent();

Write a code segment that holds all 4 people in a single array, and then uses a loop to print off the
saySomething method for each of the people.

public class Main {


public static void main(String[] args) {
Person[] people = {
new Person(),
new Employee(),
new Student(),
new APStudent()
};

for (Person person : people) {


person.saySomething();
}
}
}
Unit 9: Inheritance​ ​ ​ ​ ​ ​ ​ ​ ​ Name: __________________
9.7 – Upcasting and Aliasing

The following classes start creating an inheritance hierarchy of the Dungeons and Dragons monsters. Use the
classes below to answer the questions that follow.

public class Monster {


private String size;
private String lang;

/* Constructors Not Shown */

public String makeSound(){


return "AARRGG";
}
public String getSize(){
return size;
}
public String getLanguage(){
return lang;
}
}

public class Beholder extends Monster {


private int hp;

/* Constructors Not Shown */

public int getHP(){


return hp;
}
public String makeMovement(){
return "Flying";
}
}

public class Dragon extends Monster {


private String subtrace;

/* Constructors Not Shown */

public String makeSound(){


return "RROOAARR";
}
public String getSubtrace(){
return subtrace;
}
}

public class Giant extends Monster {


private int ac;
/* Constructors Not Shown */

public int getAC(){


return ac;
}
public String makeSound(){
return "FEE FI FO FUM";
}
}

public class FrostGiant extends Giant{


private int lifespan;

/* Constructors Not Shown */

public int getLifeSpan(){


return lifespan;
}
}

1) On each line, circle if the code segment is legal or illegal (produces a syntax error).

Monster montey = new Monster();​ ​ Legal / Illegal


Beholder eyes = new Beholder();​ ​ Legal / Illegal
Beholder octopus = new Monster();​ ​ Legal / Illegal
Dragon draco = new Monster();​​ ​ Legal / Illegal
Monster gem = new Dragon();​ ​ ​ Legal / Illegal
Monster scary = new FrostGiant();​ ​ Legal / Illegal
Monster titian = new Giant();​​ ​ Legal / Illegal
Giant frosty = new FrostGiant();​ ​ Legal / Illegal
FrostGiant snowball = new Monster();​ Legal / Illegal
Dragon goku = new Giant();​ ​ ​ Legal / Illegal

2) For the following code segments, comment on if they are legal or illegal (produces a syntax error). Then give
a sentence as to why.

Code Result and Why

Beholder dude = new Beholder(); Legal, as Beholder inherits getLanguage from


String lang = dude.getLanguage(); Monster

Giant guy = new FrostGiant();


int life = guy.getLifeSpan(); Illegal, as Giant objects cannot access getLifeSpan
Monster frank = new Dragon(); Legal, as the Monster object has a method
frank.makeSound(); makeSound

FrostGiant yeti = new FrostGiant(); Legal, FrostGiant object inherits the getSize method
int size = yeti.getSize(); from Giant (which gets it from Monster)

FrostGiant betty = new Giant(); Illegal, a Giant object cant be assigned to a


int life = betty.getLifeSpan(); FrostGiant reference as not all Giants are FrostGiants

Monster vegeta = new Dragon(); Illegal, the Monster object doesnt have the
String n = vegeta.getSubtrace(); getSubtrace method

3) The following is an Animal class:

public class Animal {


private String species;
private int weight;

public Animal(String s, int w){


species = s;
weight = w;
}

public void setWeight(int x){ weight = x;}


public int getWeight(){ return weight; }

An Elephant is a subclass of Animal. An elephant adds its own instance variable called trunkLength
that represents the length of the elephant's trunk in inches. The Elephant class adds four additional methods:
●​ eatMeal – this method increases the weight of the elephant by 20 pounds
●​ walkAround – this method decrease the weight of the elephant by 5 pounds
●​ grow – this method increase the trunk length by weight MOD 4
●​ toString – this method returns a String that displays the elephant's weight and trunk length

In the main method, an ArrayList of Elephants is created. The output of the code below is shown.

Code in main method Output


ArrayList<Elephant> enclosure = new
ArrayList<Elephant>();
enclosure.add(new Elephant(80));
enclosure.add(new Elephant(75));
enclosure.add(new Elephant(84)); weight = 200 trunkLength = 80.0
enclosure.get(2).eatMeal(); weight = 195 trunkLength = 75.0
enclosure.get(1).walkAround(); weight = 220 trunkLength = 84.0
enclosure.get(0).grow();
System.out.println(enclosure.get(0).toString());
System.out.println(enclosure.get(1).toString());
System.out.println(enclosure.get(2).toString());
Create the complete Elephant class so that it works with the code above and has the required methods.

import java.util.ArrayList;

public class Elephant extends Animal {


private double trunkLength;

public Elephant(int weight) {


super("Elephant", weight);
this.trunkLength = weight;
}

public void eatMeal() {


super.setWeight(super.getWeight() + 20);
}

public void walkAround() {


super.setWeight(super.getWeight() - 5);
}

public void grow() {


trunkLength += super.getWeight() % 4;
}

public String toString() {


return "weight = " + super.getWeight() + " trunkLength = " +
trunkLength;
}
}
Unit 9: Inheritance​ ​ ​ ​ ​ ​ ​ ​ ​ Name: _________________
9.1 – Superclasses and Subclasses

The following classes start creating an inheritance hierarchy of the Dungeons and Dragons monsters. Use the
classes below to answer the questions that follow.

public class Monster {


private String size;
private String lang;

/* Constructors Not Shown */

public String makeSound(){


return "AARRGG";
}
public String getSize(){
return size;
}
public String getLanguage(){
return lang;
}
}

public class Beholder extends Monster {


private int hp;

/* Constructors Not Shown */

public int getHP(){


return hp;
}
public String makeMovement(){
return "Flying";
}
}

public class Dragon extends Monster {


private String subtrace;

/* Constructors Not Shown */

public String makeSound(){


return "RROOAARR";
}
public String getSubtrace(){
return subtrace;
}
}

public class Giant extends Monster {


private int ac;
/* Constructors Not Shown */

public int getAC(){


return ac;
}
public String makeSound(){
return "FEE FI FO FUM";
}
}

public class FrostGiant extends Giant{


private int lifespan;

/* Constructors Not Shown */

public int getLifeSpan(){


return lifespan;
}
}

1) UML is an acronym that stands for Unified Modeling Language. A UML diagram is a way to visually
represent the contents of a program. It is very similar to the inheritance hierarchy diagrams we created in class,
but the instance variables and method names are listed under the class names, to help identify the class
components. Complete the UML diagram below that has already been started for you (we will come back to this
example in the future homework assignments as well).
2) Below each class, list the instance variables that each class member will have when instantiated.

Monster Beholder Dragon Giant FrostGiant


size, lang size, lang, size, lang, size, lang, size, lang,
hp subtrace ac ac, lifespan

3) Use the following code to create an inheritance hierarchy chart and answer the questions that follow.

public class G
{ /* code not shown */ }

public class J extends G


{ /* code not shown */ }

public class P extends G


{ /* code not shown */ }

public class Q extends J


{ /* code not shown */ }

public class T extends J


{ /* code not shown */ }

public class A extends P


{ /* code not shown */ }

2) Create an inheritance hierarchy in the space below. Then use it answer the true/false statements to the right
by circling the correct result.

G
/\ T / F a) J is a G
J P
/\ \ T / F b) Q is a P
Q T A
T / F c) A is a T

T / F d) Q is a G

T / F e) A is a P

T / F f) J is a P
Unit 9: Inheritance​ ​ ​ ​ ​ ​ ​ ​ ​ Name: _________________
9.2, 9.3 & 9.4 – Methods and Constructors for Subclasses

1) Trace the main method of the program below by writing out what each line in the main method does.

public class A
{
private int x;

public A(){
​ x = 1;
​ System.out.print(“Default A ”);
}

public A(int a){


x = a;
System.out.print(“Parameter A ”);
}

public int getX(){


​ return x;
}
}

public class B extends A


{
public B(){
super(2);
System.out.println(“Default B”);
}

public B(int b){


​ System.out.println(“Parameter B”);
}
}

public class C
{
public static void main(){
A a = new A(); prints “Default A”
​ A aa = new A(10); “Parameter A”
​ B b = new B(); “Parameter A Default B”
​ B bb = new B(5); “Parameter B” ​ ​ ​ ​
System.out.println(aa.getX()); 10
​ System.out.println(bb.getX()); 0
​ System.out.println(a.getX()); 1
​ System.out.println(b.getX()); 2
}
}
2) For the following classes, write the code for the appropriate constructor description.

public class Monster {


private String size;
private String lang;

/*Constructors in the box below*/

public Monster(){
size = "medium";
●​ Monster should have a default
lang = "common";
} constructor with size equal to
“medium” and lang equal to
public Monster(String size, String lang){ “common”.
this.size = size; ●​ Monster should have a two
this.lang = lang; parameter constructor.
}

public String makeSound(){


return "AARRGG";
}
public String getSize(){
return size;
}
public String getLanguage(){
return lang;
}
}

public class Giant extends Monster {


private int ac;

/*Constructors in the box below*/


public Giant(){
super(); ●​ Giant should have a default
constructor ac = 1; constructor, with an explicit call to
} the super’s default constructor and
ac equal to one.
public Giant(String size, String lang, int ●​ Giant should have a three
ac){ parameter constructor, with an
super(size, lang); explicit call to the super’s two
this.ac = ac; parameter constructor.
}

public int getAC(){


return ac;
}
public String makeSound(){
return "FEE FI FO FUM";
}}
public class FrostGiant extends Giant{
private int lifespan;

/*Constructors in the box below*/


public FrostGiant(){
super(); ●​ FrostGiant should have a default
lifespan = 250;
constructor, with an explicit call to
}
the super’s default constructor and
lifespan equal to 250.
public FrostGiant(int lifespan){
●​ FrostGiant should have a one
super();
this.lifespan = lifespan; parameter constructor, with an
} explicit call to the super’s default
constructor.
public FrostGiant(String size, String lang, ●​ FrostGiant should have a four
int ac, int lifespan){ parameter constructor, with an
super(size, lang, ac); explicit call to the super’s three
this.lifespan = lifespan; parameter constructor.
}

public int getLifeSpan(){


return lifespan;
}
}

3) Trace through the following lines of code and describe what they do. Assume that this code is created outside
of the object creating classes. Use the Monster, Giant, and FrostGiant code from above. Some lines of
code below have illegal syntax, while other lines of code compile without issue. Assume that all changed to the
instance variables are cumulative as the code compiles through each line.

Code Result

Monster jason = new Monster(); Calls Monster() constructor, sets size =


"medium", lang = "common".

Giant grace = new Giant(“huge”, ”giant”, Calls Giant(String, String, int), which calls
15); Monster(String, String). size = "huge", lang =
"giant", ac = 15.
Calls FrostGiant(String, String, int, int),
FrostGiant freddy = new which calls Giant(String, String, int). size =
FrostGiant(“large”, “common”, 18, 225); "large", lang = "common", ac = 18, lifespan =
225.

grace.makeSound(); Calls Giant's makeSound(), returns "FEE FI


FO FUM".

System.out.println(jason.getAC()); Compilation error


System.out.println(freddy.getAC()); Prints 18 since freddy is a FrostGiant, which
inherits getAC() from Giant.
Unit 9: Inheritance​ ​ ​ ​ ​ ​ ​ ​ ​ Name: __________________
9.6 – Polymorphism

1) Consider the following classes. Then, determine what is printed when the code in the main method is run.

public class ClassA{


/*Constructors not shown*/
public void A(int x){
System.out.println("ClassA methodA");
}
public void B(){
System.out.println("ClassA methodB");
}
}

public class ClassB extends ClassA{


/*Constructors not shown*/
public void A(int x){
System.out.println("ClassB methodA");
if(x > 10){
super.A(x);
}
else{
super.B();
}
}
public void B(){
System.out.println("ClassB methodB");
}
public void C(){
System.out.println("ClassB methodC");
}
}

public class Main {


public static void main(String[] args) {
ClassA myObj = new ClassA();
ClassB other = new ClassB();
myObj.A(10); //prints: Class A method A
other.A(11); //prints: Class B method A
myObj.B(); //prints: Class A method B
other.B(); //prints: class B method B
myObj.C(); //prints: Comp error
other.C(); //prints: Class B method C

}
}
A 2) Consider the following two classes:

public class A{
​ public int method1(int x){
​ ​ return 2;
​ }
}

public class B extends A


{ /* code not shown */}

Which of the following could be the signature of a method in class B that correctly overloads method1 in class
A?

(A) public int method1(String x)


(B) public int method1(int y)
(C) private int method1(int x)
(D) public int method2(String x)
(E) public int method2(int y)

B 3) Consider the following two classes:

public class A{
​ public int method1(int x){
​ ​ return 2;
​ }
}

public class B extends A


{ /* code not shown */}

Which of the following could be the signature of a method in class B that correctly overrides method1 in class
A?

(A) public int method1(String x)


(B) public int method1(int y)
(C) private int method1(int x)
(D) public int method2(String x)
(E) public int method2(int y)
C 4) Consider the code below.

public class Point {


private int x, y;

public Point(int theX, int theY) {


x = theX;
y = theY;
}

public display(){
System.out.print(x + “, “ + y);
}
}

public class ThreeD extends Point {


private int z;

public ThreeD(int x, int y, int theZ){


super(x, y);
z = theZ;
}

public display(){
/*implementation below*/;
}
}

The following code appears in a class outside of Point and ThreeD:

ThreeD P = new ThreeD(3, 4, 5);


P.display();

Which of the following should replace /*implementation below*/ so that the code above displays 3, 4,
5 to the console?

(A) System.out.println(super.x + “, “ + super.y + “, “ + z);

(B)
super();
System.out.println(“ , “ + z);

(C) System.out.println(x + “, “ + y + “, “ + z);

(D)
super();
System.out.println(“ , “ + super.z);

(E)
super(x, y);
System.out.println(“ , “ + super.z);
Unit 9: Inheritance​ ​ ​ ​ ​ ​ ​ ​ ​ Name: __________________
9.7 – Final, Protected, and Object Superclass

1) Consider the following classes. There are spaces and blanks in the code for you to complete the classes so
they function correctly, given their visibility modifiers. Follow the instructions given in the code comments.

public class Example {


private int a;
public int b;
protected int c;

//other instance variables, constructors, and methods not shown
//write any necessary accessor methods in the space below

​ public int getA(){


​ ​ return a;
​ }

public class SubClass extends Example{


//other instance variables, constructors, and methods not shown

//complete the blanks so that the information is displayed correctly


public void displayInfo() {
​ System.out.println(“a: “ + super.getA());
​ System.out.println(“b: “ + b);
System.out.println(“c: “ + c);
}
}

public class Driver {


public static void main(String[] args){
​ SubClass sub = new SubClass();

//complete the blanks so that the information is displayed correctly


​ System.out.println(“a: “ + sub.getA);
​ System.out.println(“b: “ + sub.b);
System.out.println(“c: “ + sub.c);
}
}

Questions 2−3 use the following code:

public class A {
​ private int i;
​public A(){
​ ​ i = 5;
​}
​public boolean equals(A obj) {
​ return this.i == obj.i;
​}
}

public class B extends A {


​private int j;
​ public B(){
​ ​ super();
​ ​ j = 2;
​ }
}

D 2) Assume the following appears in a class outside of A and B:

A a = new A();
A a2 = new A();
System.out.println(a == a2);
System.out.println(a.equals(a2));

What is printed when the code above runs?

(A)​ ​ ​ (B)​ ​ ​ (C)​ ​ ​ (D)​ ​ ​ (E)


true​ ​ ​ false​ ​ ​ false​ ​ ​ true​ ​ ​ Compiler Error
true​ ​ ​ false​ ​ ​ true​ ​ ​ false

E 3) Assume the following appears in a class outside of A and B:

A b = new B();
B b2 = new B();
B b3 = b2;
System.out.println(b2 == b3);
System.out.println(b.equals(b2));
System.out.println(b.equals(b3));

What is printed when the code above runs?

(A)​ ​ ​ (B)​ ​ ​ (C)​ ​ ​ (D)​ ​ ​ (E)


true​ ​ ​ false​ ​ ​ false​ ​ ​ true​ ​ ​ true
true​ ​ ​ false​ ​ ​ true​ ​ ​ false​ ​ ​ true
true​ ​ ​ false​ ​ ​ true​ ​ ​ false​ ​ ​ false

You might also like