Lesson 3

Objectives

  • understanding the concepts of class and object
  • using contructors to initialize objects
  • overloading methods
  • static keyword
  • this keyword

Documentation

Exercises

Exercise 1

A class Robot contains:

  • One instance variable 'x' (of type int) representing the position of robot;
  • One default constructor which initialize the value to 1;
  • One change(int k) method which add to the current robot x value to k (as long as k >= 1);
  • One toString() method which returns the position of robot;

Write a class which models the class Robot . Write a class TestRobot which test Robot class.

Exercise 2

A class called Circle contains:

  • Two private instance variables: radius (of type double) and color (of type String), with default value of 1.0 and “red”, respectively.
  • Two overloaded constructors;
  • Two public methods: getRadius() and getArea().

Write a class which models the class Circle. Write a class TestCircle which test Circle class.

Exercise 3

A class called Author contains:

  • Three private instance variables: name (String), email (String), and gender (char of either 'm' or 'f');
  • One constructor to initialize the name, email and gender with the given values;
  • public Author (String name, String email, char gender) {……}
  • (There is no default constructor for Author, as there are no defaults for name, email and gender.)
  • public getters/setters: getName(), getEmail(), setEmail(), and getGender();
  • (There are no setters for name and gender, as these attributes cannot be changed.)
  • A toString() method that returns “author-name (gender) at email”, e.g., “My Name (m) at myemail@somewhere.com”.

Write the Author class. Also write a test program called TestAuthor to test the constructor and public methods.

Exercise 4

A class called MyPoint, which models a 2D point with x and y coordinates contains:

  • Two instance variables x (int) and y (int).
  • A “no-argument” (or “no-arg”) constructor that construct a point at (0, 0).
  • A constructor that constructs a point with the given x and y coordinates.
  • Getter and setter for the instance variables x and y.
  • A method setXY() to set both x and y.
  • A toString() method that returns a string description of the instance in the format “(x, y)”.
  • A method called distance(int x, int y) that returns the distance from this point to another point at the given (x, y) coordinates.
  • An overloaded distance(MyPoint another) that returns the distance from this point to the given MyPoint instance another.

Write the code for the class MyPoint. Also write a test class (called TestMyPoint) to test all the methods defined in the class.

Exercise 5

Modify Flower class from Ciclul de viaţă al obiectelor so that it keeps track of the number of constructed object. Add a method which returns the number of constructed objects. Use 'static' variables and methods for implementing this task.