Class definitions

Alberto Ferrari
Ingegneria dell'Informazione, UniPR

Concepts

  • Basic elements of class definitions:
    • fields
    • constructors
      • parameters
    • methods
      • accessor (getter)
      • mutator (setter)

BlueJ example

  • naive-ticket-machine project
  • Methods of a TicketMachine object:
    • getBalance, getPrice, insertMoney, and printTicket
  • Create one object
    • some objects cannot be constructed unless extra information is provided
  • What happens if you insert too much money into the machine do you receive any refund?
  • What happens if you do not insert enough and then try to print a ticket?
  • Take a look at the source code of the TicketMachine class.

Class definition (example)

public class TicketMachine
{
    // The price of a ticket from this machine.
    private int price;
    // The amount of money entered by a customer so far.
    private int balance;
    // The total amount of money collected by this machine.
    private int total;

    /**
     * Create a machine ...
     */
    public TicketMachine(int cost)
    {
        price = cost;
        balance = 0;
        total = 0;
    }
    ...
  }

class header

public class TicketMachine
{
  Inner part of the class omitted.
}
  • Keywords (reserved words)
    • public and class are part of the Java language
  • Convention: start names of classes with capital letters and names of objects with lowercase letters

fields, constructors, and methods

  • fields store data persistently within an object
  • constructors ensure that an object is set up properly when created
  • methods implement the behavior of an object (functionality)

class definition

public class ClassName {
    Fields
    Constructors
    Methods
}

Fields

  • Fields store data for an object to use
  • Fields are also known as instance variables
  • Syntax:
<visibility modifier> <type> <field name>;
  • Example:
private int price;

Object diagram

public class TicketMachine
{
    private int price;
    private int balance;
    private int total;
    ... Constructor and methods omitted ...
}
  • Fields in TicketMachine class
    • price stores the fixed price of a ticket
    • balance stores the amount of money inserted into the machine by a user prior to asking for a ticket to be printed
    • total stores the total amount of money inserted into the machine

Comments

  • Comments are inserted into the source code of a class to provide explanations to human readers. They have no effect on the functionality of the class.
// single-line comment

/* multi-line
comment */

Exercise

  • What do you think is the type of each of the following fields?
    • private int count;
    • private Student representative;
    • private Server host;
  • What are the names of the following fields?
    • private boolean alive;
    • private Person tutor;
    • private Game game;
  • Which of the type names in in previous exercises would you say are class names?
  • In the following field declaration from the TicketMachine class private int price;
    • does it matter which order the three words appear in?
    • Is it always necessary to have a semicolon at the end of a field declaration?
  • Write in full the declaration for a field of type int whose name is status

Pattern for field definitions

  • They usually start with the reserved word private
  • They include a type name (such as int, String, Person, etc.)
  • They include a user-chosen name for the field variable
  • They end with a semicolon

Constructors

  • Constructors allow each object to be set up properly (initialization) when it is first created
  • Constructors have the same name as the class
public class TicketMachine
{
    Fields omitted.
    /**
     * Create a machine that issues tickets of the given price.
     * ...
     */
    public TicketMachine(int cost)
    {
        price = cost;
        balance = 0;
        total = 0;
    }
    Methods omitted.
}

Note

  • In Java, all fields are automatically initialized to a default value if they are not explicitly initialized.
  • For numeric fields, the default value is zero.

Parameters passing

Parameters

  • Constructor and methods can have parameters to provide additional information for a task
  • Via parameters is the way in which both receive values from outside
  • Parameters are variables that are defined in the header of a constructor or method:
public TicketMachine(int cost)
  • formal parameters the parameter names inside a constructor or method
  • actual parameters the values passed to a constructor or method

Variable scope and lifetime

  • The scope of a variable defines the section of source code from which the variable can be accessed
  • The lifetime of a variable describes how long the variable continues to exist before it is destroyed.
    • The lifetime of a parameter is limited to a single call of a constructor or method
    • The lifetime of a field is the same as the lifetime of the object to which it belongs

Exercises

  • To what class does the following constructor belong?
    • public Student(String name)
  • How many parameters does the following constructor have, and what are their types?
    • public Book(String title, double price)
  • Can you guess what types some of the Book class’s fields might be, from the parameters in its constructor? Can you assume anything about the names of its fields?

Methods

  • Methods consist of two parts: a header and a body
  • Header example
/**
   * Return the price of a ticket.
*/
public int getPrice()
  • Body example
{
    return price;
}

Accessor (getter)

  • Accessor methods return information about the state of an object
  • An accessor usually has no parameters and contains a return statement in order to pass back that information
  • Convention name of an accessor method: getNameOfField

Mutator (setter)

  • Mutator methods change the state of an object
  • The most basic form of mutator takes a single parameter whose value is used to directly overwrite what is stored in one of an object’s fields
  • Convention name of a mutator method: setNameOfField

Exercise

  • Complete the body of the following method, whose purpose is to add the value of its parameter to a field named score
/**
 * Increase score by the given number of points.
 */
public void increase(int points)
{
  ...
}
  • Is the increase method a mutator? If so, how could you demonstrate this?

Exercise

  • Complete the following method, whose purpose is to subtract the value of its parameter from a field named price
/**
 * Reduce price by the given amount.
 */
public void discount(int amount)
{
  ...
}

print from method

  • The method System.out.println prints its parameter to the text terminal
System.out.println(something-we-want-to-print);
  • Exercises:
    • Add a method called prompt to the TicketMachine class. This should have a void return type and take no parameters. The body of the method should print the following single line of output: Please insert the correct amount of money
    • Add a showPrice method to the TicketMachine class. This should have a void return type and take no parameters. The body of the method should print: The price of a ticket is xyz cents where xyz should be replaced by the value held in the price field when the method is called

Exercises

  • Modify the constructor of TicketMachine so that it no longer has a parameter. Instead, the price of tickets should be fixed at 1,000 cents.
    • What effect does this have when you construct ticket-machine objects within BlueJ?
  • Give the class two constructors. One should take a single parameter that specifies the price, and the other should take no parameter and set the price to be a default value of your choosing.
    • Test your implementation by creating machines via the two different constructors.
  • Implement a method, empty, that simulates the effect of removing all money from the machine. This method should have a void return type, and its body should simply set the total field to zero.
    • Does this method need to take any parameters?

Conditional statement

if(perform some test that gives a true or false result) {
  Do the statements here if the test gave a true result
}
else {
  Do the statements here if the test gave a false result
}
  • example
if(amount > 0) {
  balance = balance + amount;
} else {
  System.out.println("Use a positive amount rather than: " + amount);
}

Conditional statement

  • A conditional statement takes one of two possible actions based upon the result of a test
  • Boolean expressions have only two possible values: true and false

local variables

  • A local variable is a variable declared and used within a single method. Its scope and lifetime are limited to that of the method.
  • Example:
public int refundBalance() {
  int amountToRefund;
  amountToRefund = balance;
  balance = 0;
  return amountToRefund;
}

local variables

  • Local variable declarations never have visibility modifier as part of them
  • Local variables have a scope that is limited to the statements of the method to which they belong
  • Their lifetime is the time of the method execution: they are created when a method is called and destroyed when a method finishes

Exercise

  • What is wrong with the following version of the constructor of TicketMachine?
public TicketMachine(int cost) {
    int price = cost;
    balance = 0;
    total = 0;
}
  • Try out this version in the better-ticket-machine project. Does this version compile?

Fields - parameters - local variables

  • All three kinds of variables are able to store a value
  • Fields
    • are defined outside constructors and methods
    • are used to store data that persist throughout the life of an object. As such, they maintain the current state of an object
    • have a lifetime that lasts as long as their object lasts
    • have class scope: they can be used within any of the constructors or methods of the class in which they are defined
    • as long as they are defined as private, fields cannot be accessed from anywhere outside their defining class

Fields - parameters - local variables

  • Formal parameters and local variables persist only for the period that a constructor or method executes. Their lifetime is only as long as a single call, so their values are lost between calls. As such, they act as temporary rather than permanent storage locations.
  • Formal parameters
    • are defined in the header of a constructor or method
    • receive their values from outside, being initialized by the actual parameter values that form part of the constructor or method call
    • have a scope that is limited to their defining constructor or method
  • Local variables
    • are defined inside the body of a constructor or method
    • can be initialized and used only within the body of their defining constructor or method.
    • must be initialized before they are used in an expression
    • have a scope that is limited to the block in which they are defined.

Exercises

  • Add a new method, emptyMachine, that is designed to simulate emptying the machine of money. It should reset total to be zero but also return the value that was stored in total before it was reset.
  • Rewrite the printTicket method so that it declares a local variable, amountLeftToPay. This should then be initialized to contain the difference between price and balance. Rewrite the test in the conditional statement to check the value of amountLeftToPay. If its value is less than or equal to zero, a ticket should be printed; otherwise, an error message should be printed stating the amount left to pay.

Summary (1)

  • object creation Some objects cannot be constructed unless extra information is provided.
  • field Fields store data for an object to use. Fields are also known as instance variables.
  • comment Comments are inserted into the source code of a class to provide explanations to human readers. They have no effect on the functionality of the class.
  • constructor Constructors allow each object to be set up properly when it is first created.
  • scope The scope of a variable defines the section of source code from which the variable can be accessed.
  • lifetime The lifetime of a variable describes how long the variable continues to exist before it is destroyed.

Summary (2)

  • accessor method Accessor methods return information about the state of an object.
  • mutator method Mutator methods change the state of an object.
  • conditional A conditional statement takes one of two possible actions based upon the result of a test.
  • boolean expression Boolean expressions have only two possible values: true and false. They are commonly found controlling the choice between the two paths through a conditional statement.
  • local variable A local variable is a variable declared and used within a single method. Its scope and lifetime are limited to that of the method.

Exercises (1)

  • Complete the Book class, which can be found in the book-exercise project.
  • Add two accessor methods to the class getAuthor and getTitle
  • Add two methods, printAuthor and printTitle.
  • Add a field, pages, to store the number of pages. This should be of type int, and its initial value should be passed to the single constructor, along with the author and title strings. Include an appropriate getPages accessor method for this field.
  • Add a method, printDetails, to the Book class. This should print details of the author, title, and pages to the terminal window.
  • Add a field, refNumber, to store a reference number for a library, for example. It should be of type String and initialized to the zero length string ("") in the constructor, define a mutator for it with the following header:
public void setRefNumber(String ref)

Exercises (2)

  • Add a corresponding getRefNumber accessor
  • Modify printDetails method to include printing the reference number. However, the method should print the reference number only if it has been set.
  • Modify setRefNumber mutator so that it sets the refNumber field only if the parameter is a string of at least three characters. If it is less than three, then print an error message and leave the field unchanged
  • Add a integer field, borrowed. This keeps a count of the number of times a book has been borrowed. Add a mutator, borrow, to the class. This should update the field by 1 each time it is called. Include an accessor, getBorrowed, that returns the value of this field. Modify printDetails so that it includes the value of this field with an explanatory piece of text
  • Add a boolean field, courseText. This records whether or not a book is being used as a text book on a course. The field should be set through a parameter to the constructor and the field is immutable. Provide an accessor method for it called isCourseText

Exercises (3)

  • Create a new project, heater-exercise. Create a class, Heater, that contains a single field, temperature whose type is double-precision floating point—see
  • Define a constructor that takes no parameters. The temperature field should be set to the value 15.0 in the constructor.
  • Define the mutators warmer and cooler, whose effect is to increase or decrease the value of temperature by 5.0° respectively.
  • Define an accessor method to return the value of temperature
  • Define three new double precision floating point fields: min, max, and increment.
  • The values of min and max should be set by parameters passed to the constructor.
  • The value of increment should be set to 5.0 in the constructor. Modify the definitions of warmer and cooler so that they use the value of increment rather than an explicit value of 5.0.

Exercises (4)

  • Modify the warmer method so that it will not allow the temperature to be set to a value greater than max
  • Modify cooler so that it will not allow temperature to be set to a value less than min
  • Add a method, setIncrement, that takes a single parameter of the appropriate type and uses it to set the value of increment. Add a check to this method to prevent a negative value from being assigned to increment.

Alberto Ferrari
Ingegneria dell'Informazione, UniPR
www.ce.unipr.it/~aferrari/