Answers for Quiz on Chapter 5

This page contains sample answers to the quiz on Chapter 5 of Introduction to Programming Using Java. Note that generally, there are lots of correct answers to a given question.

You are watching: A(n) ____ defines specific tasks that an object can perform.


Question1:

Object-oriented programminguses classes and objects. What are classes and what are objects?What is the relationship between classes and objects?


Answer:

When used in object-orientedprogramming, a class is a factory for creating objects. (We are talking hereabout the non-static part of the class.) An object is a collection of data andbehaviors that represent some entity (real or abstract). A class defines thestructure and behaviors of all entities of a given type. An object is oneparticular "instance" of that type of entity. For example, if Dog is aclass, then a particular dog named Lassie would be an object of type Dog.


Answer:

When a variable is of objecttype (that is, declared with a class or interface as its type rather than one of Java"sprimitive types), the value stored in the variable is not an object. Objectsexist in a part of memory called the heap, and the variable holds apointer or reference to the object. Null is a special value thatcan be stored in a variable to indicate that it does not actually point to anyobject.


Answer:

A constructor is a special kindof subroutine in a class. It has the same name as the name of the class, and ithas no return type, not even void. A constructor is called with thenew operator in order to create a new object. Its main purpose is toinitialize the newly created object, but in fact, it can do anything that theprogrammer wants it to do.


Question4:

Suppose thatKumquat is the name of a class and that fruit is a variableof type Kumquat. What is the meaning of the statement "fruit = newKumquat();"? That is, what does the computer do when it executes thisstatement? (Try to give a complete answer. The computer does severalthings.)


Answer:

This statement creates a newobject belonging to the class Kumquat, and it stores a reference tothat object in the variable fruit. More specifically, when thecomputer executes this statement, it allocates memory to hold a new object oftype Kumquat. It calls a constructor, which can initialize theinstance variables of the object as well as perform other tasks. A reference tothe new object is returned as the value of the expression "newKumquat()". Finally, the assignment statement stores the reference in thevariable, fruit. So, fruit can now be used to access the newobject.


Answer:

Instance variables and instancemethods are non-static variables and methods in a class; that is, theirdefinitions in the class are not marked with the "static" modifier.This means that theydo not belong to the class itself. Instead, they specify what variables andmethods are in an object that belongs to that class. That is, the classcontains the source code that defines instance variables and instance methods,but actual instance variables and instance methods are contained in objects,at least logically.(Such objects are called "instances" of the class.) Thus, instance variablesand instance methods are the data and the behaviors of objects.


Answer:

In object oriented programming,one class can inherit all the properties and behaviors from another class. Itcan then add to and modify what it inherits. The class that inherits is calleda subclass, and the class that it inherits from is said to be its superclass.In Java, the fact that ClassA is a subclass of ClassB isindicated in the definition of ClassA as follows:

class ClassA extends ClassB {...}
Question7:

Modify the following class so that the two instance variables are privateand there is a getter method and a setter method for each instance variable:

public class Player { String name; int score;}
Answer:

To make a variable private, just add the word "private" in front of eachdeclaration. We need two methods for each variable. One of them returns the valueof the variable. The other provides a new value for the variable.The names for these methods should follow the usual naming convention forgetter and setter methods. (Note that my setter methods use the specialvariable this so that I can use the same name for the parameterof the method as is used for the instance variable. This is a very common pattern.)

public class Player { private String name; private int score; public String getName() { return name; } public void setName(String name) { this.name = name; // ("this.name" refers to the instance variable) } public int getScore() { return score; } public void setScore(int score) { this.score = score; }}
Question8:

Explain why the class Player that is defined in the previousquestion has an instance method named toString(), even though no definitionof this method appears in the definition of the class.


Answer:

If a class is not declared to extend any class, then it automaticallyextends the class Object, which is one of the built-in classes ofJava. So in this case, Player is a direct subclass ofObject. The Object class definesa toString() method, and the Player class inheritsthis toString() method from Object. The methods andmember variables in a class include not just those defined in the class but also thoseinherited from its superclass. (However, the inherited toString() methodwill not produce a useful string representation of a Player;to get that, you would have to override toString() in thePlayer class.)


Answer:

Polymorphism refers to the factthat different objects can respond to the same method in different ways,depending on the actual type of the object. This can occur because a method canbe overridden in a subclass. In that case, objects belonging to the subclasswill respond to the method differently from objects belonging to thesuperclass.

(Note: If B is a subclass of A, then a variable of type A can refer toeither an object of type A or an object of type B. Let"s say that varis such a variable and that action() is a method in class A that isredefined in class B. Consider the statement "var.action()". Does this executethe method from class A or the method from class B? The answer is that there isno way to tell! The answer depends on what type of object var refersto, a class A object or a class B object. The method executed byvar.action() depends on the actual type of the object thatvar refers to at run time, not on the type of the variable var. This isthe real meaning of polymorphism.)


Question10:

Java uses "garbagecollection" for memory management. Explain what is meant here by garbagecollection. What is the alternative to garbage collection?


Answer:

The purpose of garbagecollection is to identify objects that can no longer be used, and to dispose ofsuch objects and reclaim the memory space that they occupy. If garbagecollection is not used, then the programmer must be responsible for keepingtrack of which objects are still in use and disposing of objects when they areno longer needed. If the programmer makes a mistake, then there is a "memoryleak," which might gradually fill up memory with useless objects until theprogram crashes for lack of memory.


Answer:

An abstract class is one that cannot be used to create objects. It exists only as a basisfor making subclasses, and it expresses all the properties and behaviors that those subclasseshave in common. In Java, a class can be marked with the modifier abstract to makeit abstract. For example,

abstract public class Vehicle { ...It will then be a syntax error to try to call a "new Vehicle" constructor.(Note: Only a class that has been marked as abstract can contain abstract instance methods.)


Answer:

"this" is a special variable in Java, which does not have to be declared. Java makes it available automatically in instance methods and constructors.It holds a reference to the object that is being constructedor that contains the instance method that is being executed (or, in terms of messages, theobject that received the message that is being processed). It provides a way to refer to"this object." If x is an instance variable, it can also be referred to asthis.x within the same class. If doSomething() is an instance method, it can also be called as this.doSomething() within the same class. (Personally,I would be happier with Java if it required the use of "this" instead of using it implicitly.)


Question13:

For this problem, you shouldwrite a very simple but complete class. The class represents a counter thatcounts 0, 1, 2, 3, 4,.... The name of the class should be Counter. Ithas one private instance variable representing the value of thecounter. It has two instance methods: increment() adds one to thecounter value, and getValue() returns the current counter value. Writea complete definition for the class, Counter.

See more: How Often Do Guys Think About Their Crush ? How Often Do Guys Think About Their Crushes


Answer:

Here is a possible answer. (Notethat the initialization of the instance variable, value, to zero is not reallynecessary, since it would be initialized to zero anyway if no explicitinitialization were provided.)

/** * An object of this class represents a counter that counts up from zero. */public class Counter { private int value = 0; // Current value of the counter. /** * Add one to the value of the counter. */ public void increment() { value++; } /** * Returns the current value of the counter. */ public int getValue() { return value; }} // end of class Counter
Question14:

This problem uses theCounter class from the previous question. The following program segment is meantto simulate tossing a coin 100 times. It should use two Counterobjects, headCount and tailCount, to count the number ofheads and the number of tails. Fill in the blanks so that it will do so:

Counter headCount, tailCount;tailCount = new Counter();headCount = new Counter();for ( int flip = 0; flip
Answer:

The variable headCountis a variable of type Counter, so the only thing that you can do withit is call the instance methods headCount.increment() andheadCount.getValue(). Call headCount.increment() to add oneto the counter. Call headCount.getValue() to discover the currentvalue of the counter. Note that you can"t get at the value of the counterdirectly, since the variable that holds the value is a privateinstance variable in the Counter object. Similarly fortailCount. Here is the program with calls to these instance methodsfilled in:

Counter headCount, tailCount;tailCount = new Counter();headCount = new Counter();for ( int flip = 0; flip headCount.increment() ; // Count a "head", using headCount else tailCount.increment() ; // Count a "tail", using tailCount}System.out.println(("There were " + headCount.getValue() + " heads.");System.out.println(("There were " + tailCount.getValue() + " tails.");

Answer:

If the value of obj is not null, then the test correctly returnsfalse. However, if the value of obj is null, thenthere is no such thing as obj.equals, and the attempt to evaluateobj.equals(null) will cause a NullPointerExceptionthat will crash the program! The correct way to test if the value of objis null is "if(obj==null)".