slides 1-35 by Adil Aslam
NB! The practical session exercises are always provided enough and to spare with an eye to fast / experienced students have exercises to solve. To this end, do not get upset if you do not get on all the task in class. Take your time and complete the tasks at home!
Task 1. Devices
Object class Device
has private instance fields: code (int
), name (String
) and price without the sales tax (double
). In addition, the object class has a static field (double
) for the sales tax (in percent). The sales tax in Estonia is 20%. Moreover, the object class should have a constructor and the following methods:
- get and set methods for all instance fields;
- method
priceWithTax
(double
) which returns the total price of the item (item price + the sales tax)- e.g. if the price without the sales tax is 100€, then the price with the tax is 120€;
- method
toString
which returns info about the item in a readable way:- e.g. item name and its price with the sales tax is 120€.
In the main class, create several devices. Print info about them.
Task 2. Static mess
Try to run the following code:
public class Person { private String name; private double height; // in meters public Person(String personName, double personHeight) { name = personName; height = personHeight; } // ski length in cm public int skiLength() { return (int) Math.round(0.85 * height * 100); } public static void main(String[] args) { System.out.println("The length of the ski is " + skiLength()); } }
Why hasn’t it been compiled? Change the code so that it could be compiled.
Hint: the concept of the program cannot be improved by simply adding static
.
Task 3. Flights
1. Object class Plane
has private instance fields: name (String
), average speed (double
) and maximum number of passengers (int
). The object class has also a constructor and the following instance methods:
- get and set methods for all the instance fields;
- method
toString
which returns info about the plane in a readable way.
2. Object class Flight
has private instance fields: destination (String
), distance to the destination (int
), plane (Plane
) and the number of sold tickets (int
). The object class has a constructor and the following instance methods:
- all the instance fields have get and set methods;
- a method (
int
) which returns the duration of the flight in minutes (use the average speed of the plane to calculate the duration of the flight); - a method (
int
) which returns the number of free seats in the plane (use the number of sold tickets and the maximum number of passengers in the plane); - method
toString
which returns info about the flight in a readable way.
3. In the main class, create at least three flights and at least two planes:
- e.g. Fokker 50 whose average speed is 530 km/h and the maximum number of passengers is 46; BN-2 whose average speed is 170 km/h and the maximum number of passengers is 9.
4. In the main class, demonstrate the use of different instance methods.