Java OOP GUIDE / WORK CARD CLASS Topics
TASK –
PART 1 – TESTING THE FOLLOWING CARD CLASS Consider
the Card class below. Create a Tester
class with a main function. Inside it,
create a Card object and output it to screen to make sure you understand how
it works. Run your program a few
times.
TASK –
PART 2 – CARD ARRAY a)
Inside
your Tester class, remove anything you have in main. b)
In
main, create an array of Cards called hand.
Its size should be six. c)
Remember
that you need to loop over the array and construct each object one at a time. d)
Again,
loop over the array and output each Card element to screen. e)
Notice
that the cards are not in order. Our
next task will be to make it possible to sort the array. TASK –
PART 3 – IMPLEMENTING COMPARABLE a)
Go
back to your Card class and find the line public class Card
and change it to b)
Notice
that the Card class now has an error.
That is because the Comparable interface requires us to implement the compareTo(Object obj) method.
c)
For
the first line of the method, we will cast obj into a Card object. The line looks like this: Card other = (Card)obj; d)
We
are now comparing the Card that we are inside (this) to the Card other. TASK –
PART 4 – SORTING THE ARRAY Since
the Card class implements Comparable, you can simply use Arrays.sort(hand) to
sort the Card array. Try it. |
|
|