0% found this document useful (0 votes)
23 views37 pages

OOP2024 JavaExercises Lab4 OOP-ClassesAndObjects

Uploaded by

24002067
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)
23 views37 pages

OOP2024 JavaExercises Lab4 OOP-ClassesAndObjects

Uploaded by

24002067
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/ 37

HaQT Object-Oriented Programming

Lab 4. OOP Exercises


Writing Good Programs
The only way to learn programming is program, program and program. Learning
programming is like learning cycling, swimming or any other sports. You can’t learn
by watching or reading books. Start to program immediately. On the other hands, to
improve your programming, you need to read many books and study how the masters
program.
It is easy to write programs that work. It is much harder to write programs that not
only work but also easy to maintain and understood by others – I call these good
programs. In the real world, writing program is not meaningful. You have to write
good programs, so that others can understand and maintain your programs.
Pay particular attention to:

1. Coding style:

ˆ Read Java code convention: ”Google Java Style Guide” or ”Java Code
Conventions - Oracle”.
ˆ Follow the Java Naming Conventions for variables, methods, and classes
STRICTLY. Use CamelCase for names. Variable and method names begin
with lowercase, while class names begin with uppercase. Use nouns for
variables (e.g., radius) and class names (e.g., Circle). Use verbs for methods
(e.g., getArea(), isEmpty()).
ˆ Use Meaningful Names: Do not use names like a, b, c, d, x, x1, x2,
and x1688 - they are meaningless. Avoid single-alphabet names like i, j, k.
They are easy to type, but usually meaningless. Use single-alphabet names
only when their meaning is clear, e.g., x, y, z for co-ordinates and i for array
index. Use meaningful names like row and col (instead of x and y, i and j,
x1 and x2), numStudents (not n), maxGrade, size (not n), and upperbound
(not n again). Differentiate between singular and plural nouns (e.g., use
books for an array of books, and book for each item).
ˆ Use consistent indentation and coding style. Many IDEs (such as Eclipse /
NetBeans) can re-format your source codes with a single click.

2. Program Documentation: Comment! Comment! and more Comment to


explain your code to other people and to yourself three days later.

3. The problems in this tutorial are certainly NOT challenging. There are tens
of thousands of challenging problems available – used in training for various
programming contests (such as International Collegiate Programming Contest
(ICPC), International Olympiad in Informatics (IOI)).

1
HaQT Object-Oriented Programming

1 Exercises on Classes
1.1 An Introduction to Classes and Instances by Example - The
Circle Class
This first exercise shall lead you through all the basic concepts in OOP.

A class called circle is designed as shown in the following class diagram. It contains:

ˆ Two private instance variables: radius (of the type double) and color (of the type
String), with default value of 1.0 and ”red”, respectively.

ˆ Two overloaded constructors - a default constructor with no argument, and a construc-


tor which takes a double argument for radius.

ˆ Two public methods: getRadius() and getArea(), which return the radius and area of
this instance, respectively.

The source codes for Circle.java is as follows:

1 /* *
* The C i r c l e c l a s s models a c i r c l e with a r a d i u s and c o l o r .
3 */
p u b l i c c l a s s C i r c l e { // Save a s ” C i r c l e . j a v a ”
5

// p r i v a t e i n s t a n c e v a r i a b l e , not a c c e s s i b l e from o u t s i d e t h i s c l a s s
7 p r i v a t e double r a d i u s ;
private String color ;
9
// C o n s t r u c t o r s ( o v e r l o a d e d )
11 /* *
* Constructs a Circle instance with default value for radius and color
13 */
p u b l i c C i r c l e ( ) { // 1 s t ( d e f a u l t ) c o n s t r u c t o r

2
HaQT Object-Oriented Programming

15 radius = 1.0;
c o l o r = ” red ” ;
17 }

19 /* *
* Constructs a Circle instance with the given radius and default color
21 */
p u b l i c C i r c l e ( d o u b l e r ) { // 2nd c o n s t r u c t o r
23 radius = r ;
c o l o r = ” red ” ;
25 }

27 /* *
* Returns t h e r a d i u s
29 */
p u b l i c double getRadius ( ) {
31 return radius ;
}
33
/* *
35 * Returns t h e a r e a o f t h i s C i r c l e i n s t a n c e
*/
37 p u b l i c d o u b l e getArea ( ) {
r e t u r n r a d i u s * r a d i u s * Math . PI ;
39 }
}

Compile ”Circle.java”. Can you run the Circle class? Why?


ˆ This Circle class does not have a main() method. Hence, it cannot be run directly.
This Circle class is a ”building block” and is meant to be used in another program.
Let us write a test program called TestCircle (in another source file called TestCircle.java)
which uses the Circle class, as follows:

/* *
2 * A Test D r i v e r f o r t h e C i r c l e c l a s s
*/
4 p u b l i c c l a s s T e s t C i r c l e { // Save a s ” T e s t C i r c l e . j a v a ”
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
6 // D e c l a r e an i n s t a n c e o f C i r c l e c l a s s c a l l e d c i r c l e 1 .
// Construct the instance circle1 by invoking the ”default” constructor
8 // which sets its radius and color to their default value .
C i r c l e c i r c l e 1 = new C i r c l e ( ) ;
10 // Invoke p u b l i c methods on i n s t a n c e c i r c l e 1 , v i a dot o p e r a t o r .
System . out . p r i n t l n ( ”The c i r c l e has r a d i u s o f ”
12 + c i r c l e 1 . g e t R a d i u s ( ) + ” and a r e a o f ” + c i r c l e 1 . getArea ( ) ) ;
//The c i r c l e has r a d i u s o f 1 . 0 and a r e a o f 3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3

3
HaQT Object-Oriented Programming

14
// D e c l a r e an i n s t a n c e o f c l a s s c i r c l e c a l l e d c i r c l e 2 .
16 // Construct the instance circle2 by invoking the second constructor
// with t h e g i v e n r a d i u s and d e f a u l t c o l o r .
18 C i r c l e c i r c l e 2 = new C i r c l e ( 2 . 0 ) ;
// Invoke p u b l i c methods on i n s t a n c e c i r c l e 2 , v i a dot o p e r a t o r .
20 System . out . p r i n t l n ( ”The c i r c l e has r a d i u s o f ”
+ c i r c l e 2 . g e t R a d i u s ( ) + ” and a r e a o f ” + c i r c l e 2 . getArea ( ) ) ;
22 // The c i r c l e has r a d i u s o f 2 . 0 and a r e a o f 1 2 . 5 6 6 3 7 0 6 1 4 3 5 9 1 7 2
}
24 }

Now, run the TestCircle and study the results.

More Basic OOP Concepts


1. Constructor: Modify the class Circle to include a third constructor for constructing
a Circle instance with two arguments - a double for radius and a String for color.

// 3rd constructor to construct a new instance of Circle with the given radius and color
2 p u b l i c C i r c l e ( double r , S t r i n g c ) {
......
4 }

Modify the test program TestCircle to construct an instance of Circle using this
constructor.
2. Getter: Add a getter for variable color for retrieving the color of this instance.

// G e t t e r f o r i n s t a n c e v a r i a b l e c o l o r
2 public String getColor () {
......
4 }

Modify the test program to test this method.


3. public vs. private: In TestCircle, can you access the instance variable radius
directly (e.g., System.out.println(circle1.radius)); or assign a new value to radius (e.g.,
circle1.radius = 5.0)? Try it out and explain the error messages.
4. Setter: Is there a need to change the values of radius and color of a Circle instance
after it is constructed? If so, add two public methods called setters for changing the
radius and color of a Circle instance as follows:

4
HaQT Object-Oriented Programming

// S e t t e r f o r i n s t a n c e v a r i a b l e r a d i u s
2 p u b l i c v o i d s e t R a d i u s ( d o u b l e newRadius ) {
r a d i u s = newRadius ;
4 }

6 // S e t t e r f o r i n s t a n c e v a r i a b l e c o l o r
p u b l i c v o i d s e t C o l o r ( S t r i n g newColor ) {
8 ......
}

Modify the TestCircle to test these methods, e.g.,

1 C i r c l e c i r c l e 4 = new C i r c l e ( ) ; // construct an instance of Circle


c i r c l e 4 . setRadius ( 5 . 5 ) ; // change r a d i u s
3 System . out . p r i n t l n ( ” r a d i u s i s : ” + c i r c l e 4 . g e t R a d i u s ( ) ) ; // P r i n t
,→ r a d i u s v i a g e t t e r

5 c i r c l e 4 . setColor ( ” green ” ) ; // Change c o l o r


System . out . p r i n t l n ( ” c o l o r i s : ” + c i r c l e 4 . g e t C o l o r ( ) ) ; // P r i n t
,→ c o l o r v i a g e t t e r
7
// You cannot do t h e f o l l o w i n g b e c a u s e s e t R a d i u s ( ) r e t u r n s void ,
9 // which cannot be p r i n t e d
System . out . p r i n t l n ( c i r c l e 4 . s e t R a d i u s ( 4 . 4 ) ) ;

5. Keyword ”this”: Instead of using variable names such as r (for radius) and c (for
color) in the methods’ arguments, it is better to use variable names radius (for radius)
and color (for color) and use the special keyword ”this” to resolve the conflict between
instance variables and methods’ arguments. For example,

// I n s t a n c e v a r i a b l e
2 p r i v a t e double r a d i u s ;

4 /* *
* Constructs a Circle instance with the given radius and default color
6 */
p u b l i c C i r c l e ( double r a d i u s ) {
8 this . radius = radius ; // ”this.radius” refers to the instance variable
// ” r a d i u s ” r e f e r s t o t h e method ’ s parameter
10 c o l o r = ” red ” ;
}
12
/* *
14 * Sets the radius to the given value

5
HaQT Object-Oriented Programming

*/
16 p u b l i c void setRadius ( double r a d i u s ) {
this . radius = radius ; // ”this.radius” refers to the instance variable
18 // ” r a d i u s ” r e f e r s t o t h e method ’ s argument
}

Modify ALL the constructors and setters in the Circle class to use the keyword ”this”.

6. Method toString(): Every well-designed Java class should contain a public method
called toString() that returns a description of the instance (in the return type of
String). The toString() method can be called explicitly (via instanceName.toString())
just like any other method; or implicitly through println(). If an instance is passed to
the println(anInstance) method, the toString() method of that instance will be invoked
implicitly. For example, include the following toString() methods to the Circle class:

1 /* *
* Return a s e l f = d e s c r i p t i v e s t r i n g o f t h i s i n s t a n c e i n t h e
3 * form o f C i r c l e [ r a d i u s = ? , c o l o r = ? ]
*/
5 public String toString () {
r e t u r n ”Circle[radius = ” + r a d i u s + ” c o l o r = ” + c o l o r + ” ] ” ;
7 }

Try calling toString() method explicitly, just like any other method:

1 C i r c l e c i r c l e 5 = new C i r c l e ( 5 . 5 ) ;
System . out . p r i n t l n ( c i r c l e 5 . t o S t r i n g ( ) ) ; // e x p l i c i t c a l l

toString() is called implicitly when an instance is passed to println() method, for


example,

C i r c l e c i r c l e 6 = new C i r c l e ( 6 . 6 ) ;
2 System . out . p r i n t l n ( c i r c l e 6 . t o S t r i n g ( ) ) ; // e x p l i c i t c a l l
System . out . p r i n t l n ( c i r c l e 6 ) ; // p r i n t l n ( ) c a l l s t o S t r i n g
,→ ( ) i m p l i c i t l y , same a s above
4 System . out . p r i n t l n ( ” Operator ’+ ’ i n v o k e s t o S t r i n g ( ) t o o : ” + c i r c l e 6
,→ ) ; // ’+ ’ i n v o k e s t o S t r i n g ( ) t o o

The final class diagram for the Circle class is as follows:

6
HaQT Object-Oriented Programming

1.2 Another Circle Class


A class called Circle, which models a circle with a radius, is designed as shown in the
following class diagram. Write the Circle class.

Below is a test driver to test your Circle class.

/* *
2 * Test D r i v e r t o t e s t C i r c l e c l a s s
*/
4 p u b l i c c l a s s TestMain {

6 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
// Test C o n s t r u c t o r s and t o S t r i n g ( )
8 C i r c l e c i r c l e 1 = new C i r c l e ( 1 . 1 ) ;
System . out . p r i n t l n ( c i r c l e 1 ) ; // t o S t r i n g ( )
10 C i r c l e c i r c l e 2 = new C i r c l e ( ) ; // d e f a u l t c o n s t r u c t o r
System . out . p r i n t l n ( c i r c l e 2 ) ;

7
HaQT Object-Oriented Programming

12
// Test s e t t e r and g e t t e r
14 c i r c l e 1 . setRadius ( 2 . 2 ) ;
System . out . p r i n t l n ( c i r c l e 1 ) ; // t o S t r i n g ( )
16 System . out . p r i n t l n ( ” r a d i u s i s : ” + c i r c l e 1 . g e t R a d i u s ( ) ) ;

18 // Test getArea ( ) and g e t C i r c u m f e r e n c e ( )


System . out . p r i n t f ( ” a r e a i s : %.2 f%n” , c i r c l e 1 . getArea ( ) ) ;
20 System . out . p r i n t f ( ” c i r c u m f e r e n c e i s : %.2 f%n” , c i r c l e 1 .
,→ g e t C i r c u m f e r e n c e ( ) ) ;
}
22 }

The expected output is:

Command window

Circle [ radius = 1.1]


2 Circle [ radius = 1.0]
Circle [ radius = 2.2]
4 radius i s : 2.2
area i s : 15.21
6 circumference i s : 13.82

1.3 The Rectangle Class


A class called Rectangle, which models a rectangle with a length and a width (in f loat), is
designed as shown in the following class diagram. Write the Rectangle class.

Below is a test driver to test the Rectangle class:

8
HaQT Object-Oriented Programming

/* *
2 * Test D r i v e r t o t e s t R e c t a n g l e c l a s s
*/
4 p u b l i c c l a s s TestMain {

6 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
// Test c o n s t r u c t o r s and t o S t r i n g ( )
8 // You need t o append a ’ f ’ o r ’F ’ t o a f l o a t l i t e r a l
R e c t a n g l e r e c t a n g l e 1 = new R e c t a n g l e ( 1 . 2 f , 3 . 4 f ) ;
10 System . out . p r i n t l n ( r e c t a n g l e 1 ) ; // t o S t r i n g ( )
R e c t a n g l e r e c t a n g l e 2 = new R e c t a n g l e ( ) ; // d e f a u l t c o n s t r u c t o r
12 System . out . p r i n t l n ( r e c t a n g l e 2 ) ;

14 // Test s e t t e r s and g e t t e r s
rectangle1 . setLength ( 5 . 6 f ) ;
16 r e c t a n g l e 1 . setWidth ( 7 . 8 f ) ;
System . out . p r i n t l n ( r e c t a n g l e 1 ) ; // t o S t r i n g ( )
18 System . out . p r i n t l n ( ” l e n g t h i s : ” + r e c t a n g l e 1 . ge t Le n g th ( ) ) ;
System . out . p r i n t l n ( ” width i s : ” + r e c t a n g l e 1 . getWidth ( ) ) ;
20
// Test getArea ( ) and g e t P e r i m e t e r ( )
22 System . out . p r i n t f ( ” a r e a i s : %.2 f%n” , r e c t a n g l e 1 . getArea ( ) ) ;
System . out . p r i n t f ( ”perimeter is: %.2 f%n” , r e c t a n g l e 1 . g e t P e r i m e t e r ( ) ) ;
24 }
}

The expected output is:

Command window

1 R e c t a n g l e [ l e n g t h = 1 . 2 , width = 3 . 4 ]
R e c t a n g l e [ l e n g t h = 1 . 0 , width = 1 . 0 ]
3 R e c t a n g l e [ l e n g t h = 5 . 6 , width = 7 . 8 ]
length i s : 5.6
5 width i s : 7 . 8
area i s : 43.68
7 perimeter i s : 26.80

1.4 The Employee Class


A class called Employee, which models an employee with an ID, name and salary, is designed
as shown in the following class diagram. The method raiseSalary(percent) increases the salary
by the given percentage. Write the Employee class.

9
HaQT Object-Oriented Programming

Below is a test driver to test the Employee class:

1 /* *
* Test d r i v e r t o t e s t Employee c l a s s
3 */
p u b l i c c l a s s TestMain {
5

p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
7 // Test c o n s t r u c t o r and t o S t r i n g ( )
Employee employee1 = new Employee ( 8 , ” P e t e r ” , ”Tan” , 2 5 0 0 ) ;
9 System . out . p r i n t l n ( employee1 ) ; // t o S t r i n g ( ) ;

11 // Test S e t t e r s and G e t t e r s
employee1 . s e t S a l a r y ( 9 9 9 ) ;
13 System . out . p r i n t l n ( e1 ) ; // t o S t r i n g ( ) ;
System . out . p r i n t l n ( ” i d i s : ” + employee1 . getID ( ) ) ;
15 System . out . p r i n t l n ( ” f i r s t n a m e i s : ” + employee1 . getFirstName ( ) ) ;
System . out . p r i n t l n ( ” l a s t na m e i s : ” + employee1 . getLastName ( ) ) ;
17 System . out . p r i n t l n ( ” s a l a r y i s : ” + employee1 . g e t S a l a r y ( ) ) ;

19 System . out . p r i n t l n ( ”name i s : ” + employee1 . getName ( ) ) ;


System . out . p r i n t l n ( ” annual s a l a r y i s : ” + employee1 . g e t A n n u a l S a l a r y ( )
,→ ) ; // Test method
21

// Test r a i s e S a l a r y ( )
23 System . out . p r i n t l n ( employee1 . r a i s e S a l a r y ( 1 0 ) ) ;
System . out . p r i n t l n ( employee1 ) ;
25 }

10
HaQT Object-Oriented Programming

The expected out is:

Command window

Employee [ i d = 8 , name = P e t e r Tan , s a l a r y = 2 5 0 0 ]


2 Employee [ i d = 8 , name = P e t e r Tan , s a l a r y = 9 9 9 ]
id i s : 8
4 firstname i s : Peter
l a s t n a m e i s : Tan
6 s a l a r y i s : 999
name i s : P e t e r Tan
8 annual s a l a r y i s : 11988
1098
10 Employee [ i d = 8 , name = P e t e r Tan , s a l a r y = 1 0 9 8 ]

1.5 The InvoiceItem Class


A class called InvoiceItem, which models an item of an invoice, with ID, description, quantity
and unit price, is designed as shown in the following class diagram. Write the InvoiceItem
class.

Below is a test driver to test the InvoiceItem class:

11
HaQT Object-Oriented Programming

/* *
2 * Test D r i v e r t o t e s t I n v o i c e I t e m c l a s s
*/
4 p u b l i c c l a s s TestMain {

6 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
// Test c o n s t r u c t o r and t o S t r i n g ( )
8 I n v o i c e I t e m i n v 1 = new I n v o i c e I t e m ( ”A101” , ”Pen Red” , 8 8 8 , 0 . 0 8 ) ;
System . out . p r i n t l n ( i n v 1 ) ; // t o S t r i n g ( ) ;
10
// Test S e t t e r s and G e t t e r s
12 i n v 1 . setQty ( 9 9 9 ) ;
inv1 . setUnitPrice ( 0 . 9 9 ) ;
14 System . out . p r i n t l n ( i n v 1 ) ; // t o S t r i n g ( ) ;
System . out . p r i n t l n ( ” i d i s : ” + i n v 1 . getID ( ) ) ;
16 System . out . p r i n t l n ( ” d e s c i s : ” + i n v 1 . g e t D e s c ( ) ) ;
System . out . p r i n t l n ( ” qty i s : ” + i n v 1 . getQty ( ) ) ;
18 System . out . p r i n t l n ( ” u n i t P r i c e i s : ” + i n v 1 . g e t U n i t P r i c e ( ) ) ;

20 // Test g e t T o t a l ( )
System . out . p r i n t l n ( ”The t o t a l i s : ” + i n v 1 . g e t T o t a l ( ) ) ;
22 }
}

The expected output is:

Command window

1 I n v o i c e I t e m [ i d = A101 , d e s c = Pen Red , qty = 8 8 8 , u n i t P r i c e = 0 . 0 8 ]


I n v o i c e I t e m [ i d = A101 , d e s c = Pen Red , qty = 9 9 9 , u n i t P r i c e = 0 . 9 9 ]
3 i d i s : A101
d e s c i s : Pen Red
5 qty i s : 999
unitPrice i s : 0.99
7 The t o t a l i s : 9 8 9 . 0 1

1.6 The Account Class


A class called Account, which models a bank account of a customer, is designed as shown in
the following class diagram. The methods credit(amount) and debit(amount) add or subtract
the given amount to the balance. The method transferTo(anotherAccount, amount) transfers
the given amount from this Account to the given anotherAccount. Write the Account class.

12
HaQT Object-Oriented Programming

Below is a test driver to test the Account class:

1 /* *
* Test d r i v e r t o t e s t Account c l a s s
3 */
p u b l i c c l a s s TestMain {
5
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
7 // Test c o n s t r u c t o r and t o S t r i n g ( )
Account a c c o u n t 1 = new Account ( ”A101” , ”Tan Ah Teck ” , 8 8 ) ;
9 System . out . p r i n t l n ( a c c o u n t 1 ) ; // t o S t r i n g ( ) ;
Account a c c o u n t 2 = new Account ( ”A102” , ”Kumar” ) ; // d e f a u l t b a l a n c e
11 System . out . p r i n t l n ( a c c o u n t 2 ) ;

13 // Test G e t t e r s
System . out . p r i n t l n ( ”ID : ” + a c c o u n t 1 . getID ( ) ) ;
15 System . out . p r i n t l n ( ”Name : ” + a c c o u n t 1 . getName ( ) ) ;
System . out . p r i n t l n ( ” Balance : ” + a c c o u n t 1 . g e t B a l a n c e ( ) ) ;
17
// Test c r e d i t ( ) and d e b i t ( )
19 account1 . c r e d i t (100) ;
System . out . p r i n t l n ( a c c o u n t 1 ) ;
21 account1 . debit (50) ;
System . out . p r i n t l n ( a c c o u n t 1 ) ;
23 a c c o u n t 1 . d e b i t ( 5 0 0 ) ; // d e b i t ( ) e r r o r
System . out . p r i n t l n ( a c c o u n t 1 ) ;
25

// Test t r a n s f e r ( )
27 a c c o u n t 1 . t r a n s f e r T o ( account2 , 1 0 0 ) ; // t o S t r i n g ( )
System . out . p r i n t l n ( a c c o u n t 1 ) ;
29 System . out . p r i n t l n ( a c c o u n t 2 ) ;

13
HaQT Object-Oriented Programming

}
31 }

The expected output is:

Command window

1 Account [ i d = A101 , name = Tan Ah Teck , b a l a n c e = 8 8 ]


Account [ i d = A102 , name = Kumar , b a l a n c e = 0 ]
3 ID : A101
Name : Tan Ah Teck
5 Balance : 88
Account [ i d = A101 , name = Tan Ah Teck , b a l a n c e = 1 8 8 ]
7 Account [ i d = A101 , name = Tan Ah Teck , b a l a n c e = 1 3 8 ]
Amount e x c e e d e d b a l a n c e
9 Account [ i d = A101 , name = Tan Ah Teck , b a l a n c e = 1 3 8 ]
Account [ i d = A101 , name = Tan Ah Teck , b a l a n c e = 3 8 ]
11 Account [ i d = A102 , name = Kumar , b a l a n c e = 1 0 0 ]

1.7 The MyComplex class


A class called MyComplex, which models a complex number with real and imaginary parts,
is designed as shown in the class diagram.

It contains:

14
HaQT Object-Oriented Programming

ˆ Two instance variable named real (double) and imag (double) which stores the real
and imaginary parts of the complex number, respectively.

ˆ A constructor that creates a MyComplex instance with the given real and imaginary
values.

ˆ A default constructor that create a MyComplex at 0.0 + 0.0i.

ˆ Getters and setters for instance variables real and imag.

ˆ A method setValue() to set the value of the complex number.

ˆ A toString() that returns ”(x + yi)” where x and y are the real and imaginary parts,
respectively.

ˆ Methods isReal() and isImaginary() that returns true if this complex number is real
or imaginary, respectively.

Hints

1 r e t u r n ( imag = = 0 ) ;

ˆ A method equals(double real, double imag) that returns true if this complex number is
equal to the given complex number (real, imag).

Hints

1 r e t u r n ( t h i s . r e a l = = r e a l && t h i s . imag = = imag ) ;

ˆ An overloaded equals(MyComplex another) that returns true if this complex number


is equal to the given MyComplex instance another.

Hints

1 r e t u r n ( t h i s . r e a l = = a n o t h e r . r e a l && t h i s . imag = = a n o t h e r . imag ) ;

ˆ A method magnitude() that returns the magnitude of this complex number.

15
HaQT Object-Oriented Programming

1 magnitude ( x + y i ) = Math . s q r t ( x * x + y * y )

ˆ Methods addInto(MyComplex right) that adds and subtract the given MyComplex
instance (called right) into this instance and returns this instance.

1 (a + bi ) + ( c + di ) = (a + c ) + (b + d) i

Hints

1 return this ; // r e t u r n ” t h i s ” i n s t a n c e

ˆ Methods addNew(MyComplex right) that adds this instance with the given MyComplex
instance called right, and returns a new MyComplex instance containing the result.

Hints

1 // c o n s t r u c t a new i n s t a n c e and r e t u r n t h e c o n s t r u c t e d i n s t a n c e
r e t u r n new MyComplex ( . . . , . . . ) ;

You are required to:

1. Write the MyComplex class.

2. Write a test driver to test all the public methods defined in the class.

3. Write an application called MyComplexApp that uses the MyComplex class. The
application shall prompt the user for two complex numbers, print their values, check
for real, imaginary and equality, and carry out all the arithmetic operations.

16
HaQT Object-Oriented Programming

Command window

Enter complex number 1 ( r e a l and i m a g i n a r y p a r t ) : 1 . 1 2 . 2


2 Enter complex number 2 ( r e a l and i m a g i n a r y p a r t ) : 3 . 3 4 . 4

4 Number 1 i s : ( 1 . 1 + 2 . 2 i )
( 1 . 1 + 2 . 2 i ) i s NOT a pure r e a l number
6 ( 1 . 1 + 2 . 2 i ) i s NOT a pure i m a g i n a r y number

8 Number 2 i s : ( 3 . 3 + 4 . 4 i )
( 3 . 3 + 4 . 4 i ) i s NOT a pure r e a l number
10 ( 3 . 3 + 4 . 4 i ) i s NOT a pure i m a g i n a r y number

12 ( 1 . 1 + 2 . 2 i ) i s NOT e q u a l t o ( 3 . 3 + 4 . 4 i )
( 1 . 1 + 2.2 i ) + ( 3 . 3 + 4.4 i ) = ( 4 . 4 + 6.6000000000000005 i )

Try
A (more) complete design of MyComplex class is shown below:

ˆ Methods argument() that returns the argument of this complex number in radians
(double).

17
HaQT Object-Oriented Programming

1 a r g ( x + y i ) = Math . atan2 ( y , x ) ( i n r a d i a n s )

Note: The Math library has two arc-tangent methods, Math.atan(double) and
Math.atan2(double, double). We commonly use the Math.atan2(y, x) instead of
Math.atan(y/x) to avoid division by zero. Read the documentation of Math class in
package java.lang.

ˆ The method addInto() is renamed add(). Also added subtract() and subtractNew().

ˆ Methods multiply(MyComplex right) and divide(MyComplex right) that multiplies and


divides this instance with the given MyComplex instance right, and keeps the result
in this instance, and returns this instance.

1 ( a + b i ) * ( c + d i ) = ( ac = bd ) + ( ad + bc ) i
( a + b i ) / ( c + d i ) = [ ( a + b i ) * ( c = d i ) ] / ( c * c + d*d )

ˆ A method conjugate() that operates on this instance and returns this instance contain-
ing the complex conjugate.

conjugate (x + yi ) = x = yi

Take note that there are a few flaws in the design of this class, which was introduced solely
for teaching purpose:

ˆ Comparing doubles in equal() using ”==” may produce unexpected outcome. For
example, (2.2 + 4.4) == 6.6 returns false. It is common to define a small threshold
called EPSILON (set to about 10−8 ) for comparing floating point numbers.

ˆ The method addNew(), subtractNew() produce new instances, whereas add(), sub-
tract(), multiply(), divide() and conjugate() modify this instance. There is inconsis-
tency in the design (introduced for teaching purpose).

Also take note that methods such as add() returns an instance of MyComplex. Hence, you
can place the result inside a System.out.println() (which implicitly invoke the toString()).
You can also chain the operations, e.g., complex1.add(complex2).add(complex3) (same as
(complex1.add(complex2)).add(complex3)), or complex1.add(complex2).subtract(complex3).

18
HaQT Object-Oriented Programming

1.8 The MyPolynomial Class

A class called MyPolynomial, which models polynomials of degree-n (see equation), is de-
signed as shown in the class diagram.

cn xn + cn−1 xn−1 + · · · + c1 x + c0 .
It contains:
ˆ A constructor MyPolynomial(coeffs: double...) that takes a variable number of doubles
to initialize the coeffs array, where the first argument corresponds to c0.
ˆ The three dots is known as varargs (variable number of arguments), which is a new
feature introduced in JDK 1.5. It accepts an array or a sequence of comma-separated
arguments. The compiler automatically packs the comma-separated arguments in an
array. The three dots can only be used for the last argument of the method.

Hints

1 p u b l i c c l a s s MyPolynomial {
p r i v a t e double [ ] c o e f f s ;
3
p u b l i c MyPolynomial ( d o u b l e . . . c o e f f s ) { // v a r a r g s
5 t h i s . c o e f f s = c o e f f s ; // v a r a r g s i s t r e a t e d a s a r r a y
}
7 ......
}
9
// Test program
11 // Can i n v o k e with a v a r i a b l e number o f arguments
MyPolynomial p o l y n o m i a l 1 = new MyPolynomial ( 1 . 1 , 2 . 2 , 3 . 3 ) ;
13 MyPolynomial p o l y n o m i a l 1 = new MyPolynomial ( 1 . 1 , 2 . 2 , 3 . 3 , 4 . 4 , 5 . 5 )
,→ ;

15 // Can a l s o i n v o k e with an a r r a y

19
HaQT Object-Oriented Programming

double [ ] c o e f f s = { 1 . 2 , 3 . 4 , 5 . 6 , 7.8}
17 MyPolynomial p o l y n o m i a l 2 = new MyPolynomial ( c o e f f s ) ;

ˆ A method getDegree() that returns the degree of this polynomial.

ˆ A method toString() that returns ”cn xn + cn−1 xn−1 + · · · + c1 x + c0 .”.

ˆ A method evaluate(double x) that evaluate the polynomial for the given x, by substi-
tuting the given x into the polynomial expression.

ˆ Methods add() and multiply() that adds and multiplies this polynomial with the given
MyPolynomial instance another, and returns this instance that contains the result.

Write the MyPolynomial class. Also write a test driver (called TestMyPolynomial) to test
all the public methods defined in the class.
Question: Do you need to keep the degree of the polynomial as an instance variable in the
MyPolynomial class in Java? How about C/C++? Why?

20
HaQT Object-Oriented Programming

2 Exercises on Composition
2.1 An Introduction to OOP Composition by Example - the Au-
thor and Book Classes
This first exercise shall lead you through all the concepts involved in OOP Composition.

A class called Author (as shown in the class diagram) is designed to model a book’s author.
It contains:

ˆ Three private instance variables: name (String), email (String), and gender (char of
either ’m’ or ’f’);

ˆ One constructor to initialize the name, email and gender with the given values;

1 p u b l i c Author ( S t r i n g name , S t r i n g email , c h a r g e n d e r ) { . . . . . . }

(There is no default constructor for Author, as there are no defaults for name, email
and gender.)

ˆ public getters/setters: getName(), getEmail(), setEmail(), and getGender();


(There are no setters for name and gender, as these attributes cannot be changed.)

ˆ A toString() method that returns ”Author[name = ?, email = ?, gender = ?]”, e.g.,


”Author[name = Tan Ah Teck, email = [email protected], gender = m]”.

Write the Author class. Also write a test driver called TestAuthor to test all the public
methods, e.g.,

21
HaQT Object-Oriented Programming

1 Author ahTeck = new Author ( ”Tan Ah Teck ” , ” ahteck@nowhere . com” , ’m’ ) ; //


,→ Test t h e c o n s t r u c t o r
System . out . p r i n t l n ( ahTeck ) ; // Test t o S t r i n g ( )
3 ahTeck . s e t E m a i l ( ” paulTan@nowhere . com” ) ; // Test s e t t e r
System . out . p r i n t l n ( ”name i s : ” + ahTeck . getName ( ) ) ; // Test getter
5 System . out . p r i n t l n ( ” e a m i l i s : ” + ahTeck . g e tE m ai l ( ) ) ; // Test getter
System . out . p r i n t l n ( ” g e n d e r i s : ” + ahTeck . getGender ( ) ) ; // Test getter

A class called Book is designed (as shown in the class diagram) to model a book written by
one author. It contains:
ˆ Four private instance variables: name (String), author (of the class Author you have
just created, assume that a book has one and only one author), price (double), and
qty (int);
ˆ Two constructors:

p u b l i c Book ( S t r i n g name , Author author , d o u b l e p r i c e ) {


2 ......
}
4

22
HaQT Object-Oriented Programming

p u b l i c Book ( S t r i n g name , Author author , d o u b l e p r i c e , i n t qty ) {


6 ......
}

ˆ public methods getName(), getAuthor(), getPrice(), setPrice(), getQty(), setQty().

ˆ A toString() that returns ”Book[name = ?, Author[name = ?, email = ?, gender = ?],


price = ?, qty = ?”. You should reuse Author’s toString().

Write the Book class (which uses the Author class written earlier). Also write a test driver
called TestBook to test all the public methods in the class Book. Take Note that you have
to construct an instance of Author before you can construct an instance of Book. E.g.,

1 // C o n s t r u c t an a u t h o r i n s t a n c e
Author ahTeck = new Author ( ”Tan Ah Teck ” , ” ahteck@nowhere . com” , ’m’ ) ;
3 System . out . p r i n t l n ( ahTeck ) ; // Author ’ s t o S t r i n g ( )

5 Book dummyBook = new Book ( ” Java f o r dummy” , ahTeck , 1 9 . 9 5 , 9 9 ) ; // Test


,→ Book ’ s C o n s t r u c t o r
System . out . p r i n t l n (dummyBook) ; // Test Book ’ s t o S t r i n g ( )
7
// Test G e t t e r s and S e t t e r s
9 dummyBook . s e t P r i c e ( 2 9 . 9 5 ) ;
dummyBook . setQty ( 2 8 ) ;
11 System . out . p r i n t l n ( ”name i s : ” + dummyBook . getName ( ) ) ;
System . out . p r i n t l n ( ” p r i c e i s : ” + dummyBook . g e t P r i c e ( ) ) ;
13 System . out . p r i n t l n ( ” qty i s : ” + dummyBook . getQty ( ) ) ;
System . out . p r i n t l n ( ” Author i s : ” + dummyBook . getAuthor ( ) ) ; // Author ’ s
,→ t o S t r i n g ( )
15 System . out . p r i n t l n ( ”Author’s name is: ” + dummyBook . getAuthor ( ) . getName ( ) ) ;
System . out . p r i n t l n ( ” Author ’ s e m a i l i s : ” + dummyBook . getAuthor ( ) . g e t Em a il
,→ ( ) ) ;
17

// Use an anonymous i n s t a n c e o f Author t o c o n s t r u c t a Book i n s t a n c e


19 Book anotherBook = new Book ( ”more Java ” ,
new Author ( ” Paul Tan” , ” paul@somewhere . com” , ’m’ ) , 2 9 . 9 5 ) ;
21 System . out . p r i n t l n ( anotherBook ) ; // t o S t r i n g ( )

Take note that both Book and Author classes have a variable called name. However, it can
be differentiated via the referencing instance. For a Book instance says aBook, aBook.name
refers to the name of the book; whereas for an Author’s instance say anAuthor, anAu-
thor.name refers to the name of the author. There is no need (and not recommended) to
call the variables bookName and authorName.

Try

23
HaQT Object-Oriented Programming

1. Printing the name and email of the author from a Book instance.
(Hint: aBook.getAuthor().getName(), aBook.getAuthor().getEmail()).

2. Introduce new methods called getAuthorName(), getAuthorEmail(), getAuthorGen-


der() in the Book class to return the name, email and gender of the author of the
book. For example,

1 p u b l i c S t r i n g getAuthorName ( ) {
r e t u r n a u t h o r . getName ( ) ; // cannot u s e a u t h o r . name a s name i s
,→ p r i v a t e i n Author c l a s s
3 }

2.2 (Advanced) The Author and Book Classes Again - An Array


of Objects as an Instance Variable

In the earlier exercise, a book is written by one and only one author. In reality, a book can
be written by one or more author. Modify the Book class to support one or more authors
by changing the instance variable authors to an Author array.

Notes

ˆ The constructors take an array of Author (i.e., Author[ ]), instead of an Author in-
stance. In this design, once a Book instance is constructor, you cannot add or remove
author.

24
HaQT Object-Oriented Programming

ˆ The toString() method shall return ”Book[name = ?, authors = Author[name = ?,


email = ?, gender = ?], ......, price = ?, qty = ?]”.

You are required to:

1. Write the code for the Book class. You shall re-use the Author class written earlier.

2. Write a test driver (called TestBook) to test the Book class.

Try

1 // D e c l a r e and a l l o c a t e an a r r a y o f Authors
Author [ ] a u t h o r s = new Author [ 2 ] ;
3 a u t h o r s [ 0 ] = new Author ( ”Tan Ah Teck ” , ”AhTeck@somewhere . com” , ’m’ ) ;
a u t h o r s [ 1 ] = new Author ( ” Paul Tan” , ” Paul@nowhere . com” , ’m’ ) ;
5

// D e c l a r e and a l l o c a t e a Book i n s t a n c e
7 Book javaDummy = new Book ( ” Java f o r Dummy” , a u t h o r s , 1 9 . 9 9 , 9 9 ) ;
System . out . p r i n t l n ( javaDummy ) ; // t o S t r i n g ( )

2.3 The Author and Book Classes - Your Turn


A class called Author, which models an author of a book, is designed as shown in the class
diagram. A class called Book, which models a book written by ONE author and composes
an instance of Author as its instance variable, is also shown. Write the Author and Book
classes.

25
HaQT Object-Oriented Programming

Below is a test driver:

/* *
2 * Test d r i v e r c l a s s
*/
4 p u b l i c c l a s s TestMain {

6 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {

8 // Test Author c l a s s
Author a u t h o r 1 = new Author ( ”Tan Ah Teck ” , ” ahteck@nowhere . com” ) ;
10 System . out . p r i n t l n ( a u t h o r 1 ) ;

12 a u t h o r 1 . s e t E m a i l ( ” ahteck@somewhere . com” ) ;
System . out . p r i n t l n ( a u t h o r 1 ) ;
14 System . out . p r i n t l n ( ”name i s : ” + a u t h o r 1 . getName ( ) ) ;
System . out . p r i n t l n ( ” e m a i l i s : ” + a u t h o r 1 . g et E ma i l ( ) ) ;
16

// Test Book c l a s s
18 Book book1 = new Book ( ” 12345 ” , ” Java f o r dummies” , a1 , 8 . 8 , 8 8 ) ;
System . out . p r i n t l n ( book1 ) ;
20
book1 . s e t P r i c e ( 9 . 9 ) ;

26
HaQT Object-Oriented Programming

22 book1 . setQty ( 9 9 ) ;
System . out . p r i n t l n ( book1 ) ;
24 System . out . p r i n t l n ( ” i s b n i s : ” + book1 . getName ( ) ) ;
System . out . p r i n t l n ( ”name i s : ” + book1 . getName ( ) ) ;
26 System . out . p r i n t l n ( ” p r i c e i s : ” + book1 . g e t P r i c e ( ) ) ;
System . out . p r i n t l n ( ” qty i s : ” + book1 . getQty ( ) ) ;
28 System . out . p r i n t l n ( ” a u t h o r i s : ” + book1 . getAuthor ( ) ) ; // Author ’ s
,→ t o S t r i n g ( )
System . out . p r i n t l n ( ” a u t h o r ’ s name : ” + book1 . getAuthorName ( ) ) ;
30 System . out . p r i n t l n ( ”author’s name: ” + book1 . getAuthor ( ) . getName ( ) ) ;
System . out . p r i n t l n ( ”author’s email: ” + book1 . getAuthor ( ) . ge t Em a il ( ) ) ;
32 }
}

The expected output is:

Command window

1 Author [ name = Tan Ah Teck , e m a i l = ahteck@nowhere . com ]


Author [ name = Tan Ah Teck , e m a i l = ahteck@somewhere . com ]
3 name i s : Tan Ah Teck
e m a i l i s : ahteck@somewhere . com
5 Book [ i s b n = 1 2 3 4 5 , name = Java f o r dummies , Author [ name = Tan Ah Teck ,
e m a i l = ahteck@somewhere . com ] , p r i c e = 8 . 8 , qty = 8 8 ]
Book [ i s b n = 1 2 3 4 5 , name = Java f o r dummies , Author [ name = Tan Ah Teck ,
e m a i l = ahteck@somewhere . com ] , p r i c e = 9 . 9 , qty = 9 9 ]
7 i s b n i s : Java f o r dummies
name i s : Java f o r dummies
9 price i s : 9.9
qty i s : 99
11 a u t h o r i s : Author [ name = Tan Ah Teck , e m a i l = ahteck@somewhere . com ]
author ’ s name : Tan Ah Teck
13 author ’ s name : Tan Ah Teck
author ’ s e m a i l : ahteck@somewhere . com

2.4 The Customer and Invoice classes


A class called Customer, which models a customer in a transaction, is designed as shown in
the class diagram. A class called Invoice, which models an invoice for a particular customer
and composes an instance of Customer as its instance variable, is also shown. Write the
Customer and Invoice classes.

27
HaQT Object-Oriented Programming

Below is a test driver:

/* *
2 * Test d r i v e r c l a s s
*/
4 p u b l i c c l a s s TestMain {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
6

// Test Customer c l a s s
8 Customer customer1 = new Customer ( 8 8 , ”Tan Ah Teck ” , 1 0 ) ;
System . out . p r i n t l n ( customer1 ) ; // Customer ’ s t o S t r i n g ( )

28
HaQT Object-Oriented Programming

10
customer1 . s e t D i s c o u n t ( 8 ) ;
12 System . out . p r i n t l n ( customer1 ) ;
System . out . p r i n t l n ( ” i d i s : ” + customer1 . getID ( ) ) ;
14 System . out . p r i n t l n ( ”name i s : ” + customer1 . getName ( ) ) ;
System . out . p r i n t l n ( ” d i s c o u n t i s : ” + customer1 . g e t D i s c o u n t ( ) ) ;
16
// Test I n v o i c e c l a s s
18 I n v o i c e i n v o i c e 1 = new I n v o i c e ( 1 0 1 , c1 , 8 8 8 . 8 ) ;
System . out . p r i n t l n ( i n v 1 ) ;
20
i n v o i c e 1 . setAmount ( 9 9 9 . 9 ) ;
22 System . out . p r i n t l n ( i n v o i c e 1 ) ;
System . out . p r i n t l n ( ” i d i s : ” + i n v o i c e 1 . getID ( ) ) ;
24 System . out . p r i n t l n ( ” customer i s : ” + i n v o i c e 1 . getCustomer ( ) ) ; //
,→ Customer ’ s t o S t r i n g ( )
System . out . p r i n t l n ( ”amount i s : ” + i n v o i c e 1 . getAmount ( ) ) ;
26 System . out . p r i n t l n ( ”customer’s id is: ” + i n v o i c e 1 . getCustomerID ( ) ) ;
System . out . p r i n t l n ( ” customer ’ s name i s : ” + i n v o i c e 1 . getCustomerName
,→ ( ) ) ;
28 System . out . p r i n t l n ( ” customer ’ s d i s c o u n t i s : ” + i n v o i c e 1 .
,→ getCustomerDiscount ( ) ) ;
System . out . p r i n t f ( ”amount a f t e r d i s c o u n t i s : %.2 f%n” , i n v 1 .
,→ getAmountAfterDiscount ( ) ) ;
30 }
}

The expected output is:

Command window

1 Tan Ah Teck ( 8 8 ) ( 1 0%)


Tan Ah Teck ( 8 8 ) ( 8%)
3 i d i s : 88
name i s : Tan Ah Teck
5 discount i s : 8
I n v o i c e [ i d = 1 0 1 , customer = Tan Ah Teck ( 8 8 ) ( 8%) , amount = 8 8 8 . 8 ]
7 I n v o i c e [ i d = 1 0 1 , customer = Tan Ah Teck ( 8 8 ) ( 8%) , amount = 9 9 9 . 9 ]
i d i s : 101
9 customer i s : Tan Ah Teck ( 8 8 ) ( 8%)
amount i s : 9 9 9 . 9
11 customer ’ s i d i s : 88
customer ’ s name i s : Tan Ah Teck
13 customer ’ s d i s c o u n t i s : 8
amount a f t e r d i s c o u n t i s : 9 1 9 . 9 1

29
HaQT Object-Oriented Programming

2.5 The Customer and Account classes

The Customer class models a customer is design as shown in the class diagram. Write the
codes for the Customer class and a test driver to test all the public methods.

The Account class models a bank account, design as shown in the class diagram, composes
a Customer instance (written earlier) as its member. Write the codes for the Account class
and a test driver to test all the public methods.

30
HaQT Object-Oriented Programming

2.6 The MyPoint Class


A class called MyPoint, which models a 2D point with x and y coordinates, is designed as
shown in the class diagram.

It contains:

ˆ Two instance variables x (int) and y (int).

ˆ A default (or ”no-argument” or ”no-arg”) constructor that construct a point at the


default location of (0, 0).

ˆ A overloaded constructor that constructs a point with the given x and y coordinates.

ˆ Getter and setter for the instance variables x and y.

ˆ A method setXY() to set both x and y.

ˆ A method getXY() which returns the x and y in a 2-element int array.

ˆ A toString() method that returns a string description of the instance in the format
”(x, y)”.

ˆ A method called distance(int x, int y) that returns the distance from this point to
another point at the given (x, y) coordinates, e.g.,

MyPoint p o i n t 1 = new MyPoint ( 3 , 4 ) ;


2 System . out . p r i n t l n ( p o i n t 1 . d i s t a n c e ( 5 , 6 ) ) ;

31
HaQT Object-Oriented Programming

ˆ An overloaded distance(MyPoint another) that returns the distance from this point to
the given MyPoint instance (called another), e.g.,

MyPoint p o i n t 1 = new MyPoint ( 3 , 4 ) ;


2 MyPoint p o i n t 2 = new MyPoint ( 5 , 6 ) ;
System . out . p r i n t l n ( p o i n t 1 . d i s t a n c e ( p o i n t 2 ) ) ;

ˆ Another overloaded distance() method that returns the distance from this point to the
origin (0, 0), e.g.,

1 MyPoint p o i n t 1 = new MyPoint ( 3 , 4 ) ;


System . out . p r i n t l n ( p o i n t 1 . d i s t a n c e ( ) ) ;

You are required to:


1. Write the code for the class MyPoint. Also write a test program (called TestMyPoint)
to test all the methods defined in the class.

Hints

// O v e r l o a d i n g method d i s t a n c e ( )
2 // This v e r s i o n t a k e s two i n t s a s arguments
p u b l i c double d i s t a n c e ( i n t x , i n t y ) {
4 int xDiff = this . x = x ;
int yDiff = . . . . . .
6 r e t u r n Math . s q r t ( x D i f f * x D i f f + y D i f f * y D i f f ) ;
}
8
// This v e r s i o n t a k e s a MyPoint i n s t a n c e a s argument
10 p u b l i c d o u b l e d i s t a n c e ( MyPoint a n o t h e r ) {
i n t xDiff = t h i s . x = another . x ;
12 .......
}

1 // Test program t o t e s t a l l c o n s t r u c t o r s and p u b l i c methods


MyPoint p o i n t 1 = new MyPoint ( ) ; // Test c o n s t r u c t o r
3 System . out . p r i n t l n ( p o i n t 1 ) ; // Test t o S t r i n g ( )

5 // Test s e t t e r s
p o i n t 1 . setX ( 8 ) ;

32
HaQT Object-Oriented Programming

7 p o i n t 1 . setY ( 6 ) ;

9 // Test g e t t e r s
System . out . p r i n t l n ( ”x i s : ” + p o i n t 1 . getX ( ) ) ;
11 System . out . p r i n t l n ( ”y i s : ” + p o i n t 1 . getY ( ) ) ;
p1 . setXY ( 3 , 0 ) ; // Test setXY ( )
13 System . out . p r i n t l n ( p o i n t 1 . getXY ( ) [ 0 ] ) ; // Test getXY ( )
System . out . p r i n t l n ( p o i n t 1 . getXY ( ) [ 1 ] ) ;
15 System . out . p r i n t l n ( p o i n t 1 ) ;

17 MyPoint p o i n t 2 = new MyPoint ( 0 , 4 ) ; // Test a n o t h e r c o n s t r u c t o r


System . out . p r i n t l n ( p o i n t 2 ) ;
19
// T e s t i n g t h e o v e r l o a d e d methods d i s t a n c e ( )
21 System . out . p r i n t l n ( p o i n t 1 . d i s t a n c e ( p o i n t 2 ) ) ; // which v e r s i o n ?
System . out . p r i n t l n ( p o i n t 2 . d i s t a n c e ( p o i n t 1 ) ) ; // which v e r s i o n ?
23 System . out . p r i n t l n ( p o i n t 1 . d i s t a n c e ( 5 , 6 ) ) ; // which v e r s i o n ?
System . out . p r i n t l n ( p o i n t 1 . d i s t a n c e ( ) ) ; // which v e r s i o n ?

2. Write a program that allocates 10 points in an array of MyPoint, and initializes to


(1, 1), (2, 2), . . . , (10, 10).

Hints
You need to allocate the array, as well as each of the 10 MyPoint instances. In other
words, you need to issue 11 new, 1 for the array and 10 for the MyPoint instances.

MyPoint [ ] p o i n t s = new MyPoint [ 1 0 ] ; // D e c l a r e and a l l o c a t e an


,→ a r r a y o f MyPoint
2 f o r ( i n t i = 0 ; i < p o i n t s . l e n g t h ; i ++ ) {
p o i n t s [ i ] = new MyPoint ( . . . ) ; // Allocate each of MyPoint instances
4 }
// u s e a l o o p t o p r i n t a l l t h e p o i n t s

Notes
Point is such a common entity that JDK certainly provided for in all flavors.

2.7 The MyLine and MyPoint Classes


A class called MyLine, which models a line with a begin point at (x1, y1) and an end point
at (x2, y2), is designed as shown in the class diagram. The MyLine class uses two MyPoint
instances (written in the earlier exercise) as its begin and end points. Write the MyLine
class. Also write a test driver to test all the public methods in the MyLine class.

33
HaQT Object-Oriented Programming

2.8 The MyCircle and MyPoint Classes


A class called MyCircle, which models a circle with a center and a radius, is designed as
shown in the class diagram. The MyCircle class uses a MyPoint instance (written in the
earlier exercise) as its center.

34
HaQT Object-Oriented Programming

The class contains:


ˆ Two private instance variables: center (an instance of MyPoint) and radius (int).
ˆ A constructor that constructs a circle with the given center’s (x, y) and radius.
ˆ An overloaded constructor that constructs a MyCircle given a MyPoint instance as
center, and radius.
ˆ A default constructor that construct a circle with center at (0, 0) and radius of 1.
ˆ Various getters and setters.
ˆ A toString() method that returns a string description of this instance in the format
”MyCircle[radius = r, center = (x, y)]”. You shall reuse the toString() of MyPoint.
ˆ getArea() and getCircumference() methods that return the area and circumference of
this circle in double.
ˆ A distance(MyCircle another) method that returns the distance of the centers from
this instance and the given MyCircle instance. You should use MyPoint’s distance()
method to compute this distance.
Write the MyCircle class. Also write a test driver (called TestMyCircle) to test all the public
methods defined in the class.

Hints

1 // C o n s t r u c t o r s
p u b l i c MyCircle ( i n t x , i n t y , i n t r a d i u s ) {
3 // Need t o c o n s t r u c t an i n s t a n c e o f MyPoint f o r t h e v a r i a b l e c e n t e r
c e n t e r = new MyPoint ( x , y ) ;
5 this . radius = radius ;
}
7 p u b l i c MyCircle ( MyPoint c e n t e r , i n t r a d i u s ) {
// An instance of MyPoint already constructed by caller; simply assign .
9 this . center = center ;
......
11 }
p u b l i c MyCircle ( ) {
13 c e n t e r = new MyPoint ( . . . . . ) ; // c o n s t r u c t MyPoint i n s t a n c e
this . radius = . . . . . .
15 }

17 // Returns t h e x= c o o r d i n a t e o f t h e c e n t e r o f t h i s MyCircle
p u b l i c i n t getCenterX ( ) {
19 r e t u r n c e n t e r . getX ( ) ; // cannot use center.x and x is private in MyPoint
}
21
// Returns the distance of the center for this MyCircle and another MyCircle
23 p u b l i c d o u b l e d i s t a n c e ( MyCircle a n o t h e r ) {

35
HaQT Object-Oriented Programming

r e t u r n c e n t e r . d i s t a n c e ( a n o t h e r . c e n t e r ) ; // u s e d i s t a n c e ( ) o f MyPoint
25 }

2.9 The MyTriangle and MyPoint Classes


A class called MyTriangle, which models a triangle with 3 vertices, is designed as shown in
the class diagram. The MyTriangle class uses three MyPoint instances (created in the earlier
exercise) as the three vertices.

It contains:

ˆ Three private instance variables v1, v2, v3 (instances of MyPoint), for the three vertices.

ˆ A constructor that constructs a MyTriangle with three set of coordinates, v1 = (x1, y1),
v2 = (x2, y2), v3 = (x3, y3).

ˆ An overloaded constructor that constructs a MyTriangle given three instances of My-


Point.

ˆ A toString() method that returns a string description of the instance in the format
”MyTriangle[v1 = (x1, y1), v2 = (x2, y2), v3 = (x3, y3)]”.

ˆ A getPerimeter() method that returns the length of the perimeter in double. You
should use the distance() method of MyPoint to compute the perimeter.

ˆ A method printType(), which prints ”equilateral” if all the three sides are equal, ”isosce-
les” if any two of the three sides are equal, or ”scalene” if the three sides are different.

Write the MyTriangle class. Also write a test driver (called TestMyTriangle) to test all the
public methods defined in the class.

36
HaQT Object-Oriented Programming

2.10 The MyRectangle and MyPoint Classes


Design a MyRectangle class which is composed of two MyPoint instances as its top-left and
bottom-right corners. Draw the class diagrams, write the codes, and write the test drivers.

37

You might also like