Java Reference
In-Depth Information
Self-Check Problems
Section 8.1: Object-Oriented Programming
1. Describe the difference between object-oriented programming and procedural programming.
2. What is an object? How is an object different from a class?
3. What is the state of a String object? What is its behavior?
4. What is the output of the following program?
public class ReferenceMystery3 {
public static void main(String[] args) {
int a = 7;
int b = 9;
Point p1 = new Point(2, 2);
Point p2 = new Point(2, 2);
addToXTwice(a, p1);
System.out.println(a + " " + b + " " + p1.x + " " + p2.x);
addToXTwice(b, p2);
System.out.println(a + " " + b + " " + p1.x + " " + p2.x);
}
public static void addToXTwice(int a, Point p1) {
a = a + a;
p1.x = a;
System.out.println(a + " " + p1.x);
}
}
5. Imagine that you are creating a class called Calculator . A Calculator object could be used to program a simple
mathematical calculator device like the ones you have used in math classes in school. What state might a
Calculator object have? What might its behavior be?
Section 8.2: Object State and Behavior
6. Explain the differences between a field and a parameter. What is the difference in their syntax? What is the difference
in their scope and the ways in which they may be used?
7. Create a class called Name that represents a person's name. The class should have fields representing the person's
first name, last name, and middle initial. (Your class should contain only fields for now.)
8. What is the difference between an accessor and a mutator? What naming conventions are used with accessors and
mutators?
9. Add a new method to the Point class we developed in this chapter:
public double distance(Point other)
Returns the distance between the current Point object and the given other Point object. The distance between two
points is equal to the square root of the sum of the squares of the differences of their x - and y -coordinates. In other
words, the distance between two points ( x 1 , y 1 ) and ( x 2 , y 2 ) can be expressed as the square root of ( x 2
- x 1 ) 2 +
- y 1 ) 2 . Two points with the same ( x , y ) coordinates should return a distance of 0.0 .
( y 2
 
Search WWH ::




Custom Search