Tutorial 6 February 4th/5th, 2015 CPSC 233 Tutorial 6 February 4th/5th, 2015
Defining Classes and Mothods Java is a true OO language and therefore the underlying structure of all Java programs is classes. Anything we wish to represent in Java must be encapsulated in a class that defines the “state” and “behaviour” of the basic program components known as objects.
Classes A class is a collection of fields (data) and methods (procedure or function) that operate on that data. Circle centre radius circumference() area()
Creating objects/instances of a class Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects aCircle = new Circle() ; bCircle = new Circle() ;
Executing Methods in Object/Circle Using Object Methods: sent ‘message’ to aCircle Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area();
Constructors Circle(double r) { radius = r; } Circle() { radius = 1.0; myCircle = new Circle(5.0); Constructors are a special kind of methods that are invoked to construct objects.
Constructors, cont. A constructor with no parameters is referred to as a default constructor. Constructors must have the same name as the class itself. Constructors do not have a return type—not even void. Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.
Visibility Modifiers and Accessor Methods public The class, data, or method is visible to any class in any package. private The data or methods can be accessed only by the declaring class. The get and set methods are used to read and modify private properties
Exercise 1 Define a class called Counter. An object of this class is used to count things, so it records a count that is a nonnegative whole number.
Exercise 1 Include methods to: set the counter to zero to increase the count by 1 and to decrease the count by 1 include an accessor method that returns the current count value include a method that outputs the count to the screen
Exercise 1 Be sure that no method allows the value of the counter to become negative. The only method that can set the counter is the one that sets it to zero. Also, write a program to test your class definition.
Counter Class
CounterTest
Exercise 2 Consider a class PersonAddress that represents an entry in an address book. Its attributes are: * The first name of the person * The Last name of the person * The e-mail address of the person * The telephone number of the person It will have methods to: * Access each attribute * Change the e-mail address * Change the telephone number * Test whether two instances are equal based solely on name 1. Write a method heading for each method. 2. Write preconditions and postconditions for each method. 3. Write some Java statements that test the class. 4. Implement the class.
PersonAddress Class
PersonAddress Test