Table of Contents
Point
class.A point at the plane can be represented by a pair of coordinates x and y, both with real values. In Java, we can represent a point at the plane as an instance of the following class:
public class Point {
private double x;
private double y;
/* methods */
/* to complete */
}
In Java, the constructor of a class is used to initialise the values of the attributes at the moment the object is instantiated at runtime execution.
Program a constructor for the Point
class. It must receive both point coordinates as input parameters.
The toString()
method has a special meaning for objects in Java. This method is used to get a text representation of the object as a string.
Program the toString()
method so that it returns a string with the representation of the point according to the following format:
(x, y)
where x and y must be replaced by their respectives values. The prototype of the method is specified as follows:
public String toString() { /* ... */ }
Remember that the "+" operator, applied to strings of characters, allows to concatenate them. But if you try to concatenate a number with a string, don't worry, Java converts automaticaly the number to a string to make the "addition".
main
method.Now you have to create a class to test the previous code.
Program a class called TestingPoint
which has a main
method. This method must receive, as command line arguments, the x and y coordinates, then create a new Point
object with those coordinates and print a text representation of such object to the standard output (the console).
The program must check that the number of command line arguments received is correct.
The parseDouble()
method of the
Double class
(click to follow the link to the API Javadoc) transforms a string of characters to a double
primitive type.
It is common that object's attributes are declared as private (private
)
to avoid uncontrolled accesses from other parts of the code. To provide such access from outside code, there are
special methods. Those methods usually begin with the following strings: "get
"
(read access) and "set
" (write access).
In this paragraph, we are going to implement two auxiliary methods that will allow us to calculate distances between points.
Program a method of the Point
class that returns the distance from the point to the origin of the coordinates. The prototype of the method is as follows:
public double distanceToOrigin() {
/* complete */
}
Modify the code of your TestingPoint
class to check that its behaviour is correct.
Program a method of the Point
class that returns the distance between the point represented by
the actual object instance and another instance of Point
that is received as input parameter.
The prototype of the method is as follows:
public double distance(Point anotherPoint) {
/* completar */
}
Modify the code of your TestingPoint
class to check that its behaviour is correct.
Program a method of the Point
class that returns the quadrant in which the point is located. The prototype of the method is as follows:
It returns 0 if it is placed at the origin of coordinates or on any of the axis.
It returns 1 if it is placed at the first quadrant (both x and y positives).
It returns 2 if it is placed at the second quadrant (x negative and y positive).
It returns 3 if it is placed at the third quadrant (both x and y negatives).
It returns 4 if it is placed at the fourth quadrant (x positive and y negative).
The prototype of the method is shown below:
public int quadrant() {
/* complete */
}
Modify the code of your TestingPoint
class to check that its behaviour is correct.
This section is based on the previous methods you have implemented before.
Program a method of the Point
class that receives, as input parameter, an array of
Point
objects and returns a reference to the object of the array that represents the nearest point to the current object (this).
The prototype of the method is as follows:
public Point nearest(Point[] otherPoints) {
/* complete */
}
Modify the code of your TestingPoint
class to check that its behaviour is correct.
Triangle
class.A triangle is fully defined by three of its vertexes. These vertexes can be represented as
objects of the Point
class.
This section is based on the previous methods you have implemented before.
Program the Triangle
class with its attributes and a constrctor
that receives three points (vertexes) as input parameters.
Program a class to test it.
In this execise, we are going to create a Date
class that will allow us to work with dates. This class has to store some attributes and must define some methods that will make different basic operations.
Before start writing the code, try to think about the design of Date
class.
What kind of information must be stored in each object? If some given data can be stored in different formats, would you use several attributes to represent the same information? Why? Which format do you think is more appropriate?
What constructors would you provide? Notice that constructors have to initialize the internal object data.
Think of what methods you think would be useful to be included in the class.
Can you think of any kind of information that could be suitable to be included in the class and that is common for
all objects from Date
?
Define all attributes for Date
class.
The Date
class has to provide two constructors to initialize Date
's objects.
A constructor with three integers that represent the day, month and year, respectively.
A constructor with three strings of characters that represent the day, month and year, respectively.
Object attributes should be declared with private access to avoid making errors in their updates.
Program both get
and set
methods which are necesary to read and update encapsulated
information of Date
's objects.
toString()
method for a text representation of the object.The toString()
method has a special meaning for all objects in Java. It is used to get a String representation of the object that shows the values of the object's attributes at a given moment.
Program the toString()
method according to the following declaration:
public String toString() { /* completar */ }
This method has to return a string of characters with a text representation of a date, according to the following format (don't worry about the ordinal ("21st", "13th"):
month(text) day(number), year(number)
EXAMPLE : August 6, 2007
compareTo()
method to compare dates.The compareTo()
method has a special meaning for objects in Java. It is used to compare two objects.
RECOMMENDED READING: Consult the Java API documentation of the comparation interface at the following link Comparable. In this page, look for what value must be returned in each case of comparation of the two objects.
Program the compareTo()
method according to the following declaration:
public int compareTo(Date date) {
/* ... */
}
This method compares the date stored in the current object with the date stored in the other object that is passed as input parameter and it must return:
-1 if the date stored in the current object is previous than the date stored in the object passed as parameter.
0 if both dates are equal.
1 if the date stored in the current object is later than the date stored in the object passed as parameter.
Remember that a class can contain several methods with the same name, as long as they have distinct input parameters. This is known as method overloading.
Program an auxiliary method that returns the number of days that the month that is passed by parameter has. Overload that method so that it can be used with either the number or the name of the month. Both methods have the following declarations:
... int getDaysInMonth(int month) {
/* complete */
}
... int getDaysInMonth(String month) {
/* complete */
}
Review class declaration and object creation.
The Album
class represents the production of a singer or musical groups. This class has the following attributes:
title
: The Album title
author
: The name of the singer or group
year
: Publishing year
elements
: Number of CDs or DVDs included in the Album
price
: Suggested retail price (without VAT)
genre
: A character indicating the type of genre (D: Dance, P: Pop, R: Rock, C: Classical, J: Jazz, O: Other)
isSpanish
: True if it is an album of a Spanish singer or group
Think about the attributes, their data type and modifiers. Then implement the Album class in Java
Then implement a new class called AlbumTest
that only contains the main
method to test the Album
class. This class has to:
Create two objects of type Album
called album1
and album2
Assign a value to the attributes with data from two albums that you like
Print the information of each album correctly tabulated as shown below
Album:
Title: Crazy Hits
Author: Crazy Frog
Year: 2005
Num: 1
Price: 14.99
Genre: D
Is Spanish?: False
Review objects encapsulation and access to private attributes using public methods.
Add the necessary get
and set
to assign and retrieve the value of each attribute. For the genre
attribute, check that the character used is valid before assigning it.
Modify the main
method of AlbumTest
to use the access method defined above. Check the result.
Review arithmetic operators.
Modify AlbumTest.java
to calculate the total price of the albums (with and without VAT) and print a message on the screen like this:
Total price (without VAT): 29.98 euros
Total price (with 16% VAT): 34.7768 euros
Review constructors and their relationship to access methods.
We have not written any constructor for the Album
class yet. After creating an object of Album
class, we have to call access methods such as setTitle
or setAuthor
for assigning value to the attributes of the newly created object. As you know from past labs, this has the disadvantage that you can forget to give value to an attribute and this would result in the creation of objects with inconsistent values. In order to solve this problem you must implement a constructor method to assign value to the attributes when an object is created. To do this, you have to pass a set of parameters to the constructor. This allows us to call the constructor as follows:
new Album("Crazy Hits","Crazy Frog",2005,1,14.99,'D',false);
Review the use of constants and the switch selection statement.
Create constants to represent each different musical genre and assign its corresponding value, for instance, ROCK='R'
. Modify the setGenre
method so as to use these constants when the code checks the valid genres and assigns the value to the genre
attribute.
Review the use of classes as reference types in attribute declaration.
The album's price is something that could be changed depending on our pricing policies, seasonal offers, etc. We are going to change the price
attribute in order to get a better management of these changes. Instead of using a basic type (double) we are going to create a new type called Rate
. Thus we can declare a Rate
class to encapsulate a set of data and specific behaviour that allows to calculate the album's price.
Implement a Rate
class with the following information:
3 constants to represent different prices (NORMAL=0, REDUCED=1, INCREASED=2)
A base
attribute to represent the basic price without offers or surcharges
A plus
attribute to represent the amount that will be added or subtracted to/from the basic price
A getPrice
method that calculates the price using the following formula and returns its value:
Normal price = base*num
Reduced price (eg. seasonal offers) = base*num*(1-plus)
Increased price (eg. special edition) = base*num*(1+plus)