Constructors, Getters and Setters – Examples (Java)

Page 2 of 4 · Object-oriented programming – examples

Tasks in which an object "looks after" its own data: the constructor sets the initial values, the private attributes are changed only through methods, and toString() describes the object.

A reminder of the parts of a class we use in these tasks:

class Student {
    private String name;      // private: it cannot be changed directly outside the class
    private int grade;

    Student(String name, int grade) {  // constructor – called with new
        this.name = name;              // this.name is the attribute, name is the parameter
        this.grade = grade;
    }

    String getName() { return name; }  // getter – reads a value

    void setGrade(int grade) {         // setter – changes a value, with a check
        if (grade >= 1 && grade <= 8) this.grade = grade;
    }

    public String toString() { return name + ", grade " + grade; }
}
Before you start: read the lessons Classes and objects in Java, Objects and methods.
How to practise: write the class and the program on your own, run it on the example from the task, and only then open the hint, and finally the solution. All solutions are in Java; the helper classes are in the same file (without the word public), so the program runs as one file.
TASK 01Difficulty: easy

A student and the average grade

Make a class Student with the attributes name and three grades (in maths, language and computing) and a constructor that sets them. Add a method average() and a method toString(). In main read the data for two students and print them, and then the name of the student with the higher average.

Example

Input

Ana 5 4 5
Ivan 4 4 3

Output

Ana, average 4.67
Ivan, average 3.67
Better average: Ana
TASK 02Difficulty: easy

A piggy bank (a bank account)

Make a class Account with the private attributes owner and balance. The constructor receives the owner's name, and the initial balance is 0. The method deposit(amount) increases the balance, and withdraw(amount) decreases it only if there is enough money – otherwise it prints a message and does not change the balance. Read the name, and then a series of orders of the form D 500 (deposit) or W 200 (withdrawal), until the order E (end). At the end print the balance.

Example

Input

Mila
D 500
W 200
W 900
D 100
E

Output

Not enough money to withdraw 900
Mila: balance 400
TASK 03Difficulty: medium

A rectangle with two constructors

Make a class Rectangle with the sides a and b and two constructors: without parameters (it makes a 1×1 square) and with two parameters. Add the methods perimeter(), area() and isSquare(). Read the sides of the second rectangle and print the data for both.

Example

Input

4 4

Output

1.0 x 1.0: P = 4.0, A = 1.0, square
4.0 x 4.0: P = 16.0, A = 16.0, square
TASK 04Difficulty: medium

A thermometer with a check (setter)

The class Thermometer stores the temperature in °C. The setter setTemperature(t) accepts only values from −50 to 60; for other values it prints "Invalid measurement" and keeps the old value. Add a getter and a method inFahrenheit() (F = C·9/5 + 32). Read n measurements and after each one print the current temperature in °C and °F.

Example

Input

3
21.5
99
-3

Output

21.5 C = 70.7 F
Invalid measurement: 99.0
21.5 C = 70.7 F
-3.0 C = 26.6 F
TASK 05Difficulty: harder

A fraction

Make a class Fraction with a numerator and a denominator. The constructor reduces the fraction straight away (using the GCD). Add a method add(Fraction other) that returns a new fraction – the sum, and a method toString() that returns the form a/b. Read two fractions and print them and their sum.

Example

Input

2 4
1 3

Output

1/2
1/3
1/2 + 1/3 = 5/6
Common mistakes and tips
  • A constructor has no return type (not even void) and has the same name as the class.
  • When a parameter has the same name as an attribute, the attribute is accessed with this.name; without this only the parameter is changed.
  • A setter is the right place to check the data: e.g. a height cannot be negative, a grade must be from 1 to 5.
  • If you write a constructor with parameters, Java no longer creates the empty constructor new MyClass() – add it yourself if you need it.

Check your knowledge

Open the quiz

Mini quiz: constructors

1. When is a constructor executed?




2. Why do we make an attribute private?




3. What does this.x = x; do in a constructor?