Lab Four

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Classes and objects

1. Create a class Rectangle with attributes length and width, each of which defaults to 1. Provide
methods that calculate the rectangle’s perimeter and area. It has set and get methods for both
length and width. These methods should verify that length and width are each floating-point
numbers larger than 0.0 and less than 20.0. Write a program to test class Rectangle.
2. Create a class Heater, that contains an integer field, temperature. Every heater has a range of
temperatures it can operate in, defined by a minimum and a maximum temperature. When you
want to change the temperature, the values are updated with a certain step, defined by the
increment attribute. Define a constructor which allows you to initialise all these values. Take care
that the minimum temperature is lower than the maximum one, otherwise swap their values.
Define an accessor (getter) method to know the value of temperature. Define the mutators(setter)
warmer and cooler, whose effect is to increase or decrease the value of temperature by the value
of increment. Cooler and warmer are not allowed to change the temperature out of the given
range. It should also be possible to change the value of increment during the lifetime of the
heater. Check that increment is a positive value, otherwise print an error message on the screen.
Test your class.
3. Create a class called Rational for performing arithmetic with fractions. Write a program to test
your class. Use integer variables to represent the private instance variables of the class—the
numerator and the denominator.
a. Provide a constructor that enables an object of this class to be initialized when it is
declared.
b. Provide a no-argument constructor with default values in case no initializers are
provided.
c. Provide public methods that perform each of the following operations:
i. Add two Rational numbers
ii. Subtract two Rational numbers
iii. Multiply two Rational numbers
iv. Divide of two Rational numbers
v. e) Print Rational numbers in the form a/b, where a is the numerator and b is
the denominator.
vi. Print Rational numbers in floating-point format.

You might also like