Using Functional Decomposition - Computer Science

Card 0 of 2

Question

Consider the code below:

private static class Philosopher {

private String name;

private String favoriteSubject;

public Philosopher(String n, String f) {

name = n;

favoriteSubject = f;

}

public String getName() {

return name;

}

public String getFavoriteSubject() {

return favoriteSubject;

}

public void speak() {

System.out.println("Hello, World! My name is "+name + ". My favorite subject is "+favoriteSubject);

}

}

private static class Nominalist extends Philosopher {

boolean franciscan;

public Nominalist(String n,boolean frank) {

super(n,"logic");

franciscan = frank;

}

public void speak() {

super.speak();

if(franciscan) {

System.out.println("I am a Franciscan");

} else {

System.out.println("I am not a Franciscan");

}

}

public String whoMightHaveTaughtMe() {

if(franciscan) {

return "Perhaps William of Ockham?....";

} else {

return "Perhaps it was Durandus of St. Pourçain — scandalous, a Dominican nominalist!";

}

}

}

If you wished to make a toString() method for both Philosopher and Nominalist, using the same output as in each class' current speak () methods, what would be the best way to organize your code?

I. Have toString () invoke both classes' speak() methods.

II. Have the speak() method invoke the new toString () method.

III. Create a new subclass and write the toString() method in that.

Answer

The toString() method must return a string value. Therefore, it makes the most sense that you would have this method generate the output that you currently generate in speak(). Then, you could have speak() invoke the toString() method to output the same string data.

Compare your answer with the correct one above

Question

Given a class Thing and the code:

Thing thingOne, thingTwo;

What function call is the following equivalent to?

thingTwo = thingOne;

Answer

What's given to us is that thingOne and thingTwo have already been created, this is a vital piece of information. Let's go through each of the choices

operator=(thingTwo, thingOne);

This line of code makes no sense and is syntactically wrong.

ostream& Thing::operator=(const Thing& rhs);

This line of code says to access the "operator=" method from the "Thing" class and put it onto the ostream, this has nothing to do with assigning thingOne to thingTwo.

When we come across the choice of the copy constructor, we have to keep in mind that the copy constructor is only used when an object use to to create another one, for example we have a given class called Foo:

Foo foo;

Foo foobar = foo;

In this case, we are using foo to create foobar.

The only choice that works is:

thingTwo.operator=(thingOne);

This line of code means that the thingOne object is being assigned to thingTwo.

Compare your answer with the correct one above

Tap the card to reveal the answer