Session 3 |
Methods
So far we have been focused on the object state - a set of values stored in the instance fields. Apart from the state, an object has behavior (methods).
The behavior of an object is a collection of methods within the object.
These methods represent different actions that our client class could be able to do with the state stored in an object's fields.
Object methods can be created the same way as any other methods, but the object methods do not have the static property. Here is a general syntax to create an object method:
public returnType methodName(list_of_parameters) { //statements; }
Usually methods are defined after the instance fields and the constructors within the object class:
// Object class declaration - contains object definition (its states, constructors and behavior) public class Dog { // Instance fields for properties String name; String breed; int age; String size; String color; String accent = "bow-wow"; // all instances (objects) of this class have the same accent // Default constructor public Dog() { } // Objects are not primitive structures; we can't print them like numbers or strings // First, we have to create a method that knows in what format to print variables and values public String toString() { return ("Name: "+name+"Breed: "+breed+" Size: "+size+" Age: "+age+" Color: "+color +" Accent: "+accent); } // Method which demonstrates dog's woofing public String woofing() { return ("The dog "+name+" makes sound like "+accent); } }
Since objects are not primitive data types, we have to create a guideline on which values and in what format to be printed out. Method toString returns a String with basic information about the dog.
We can also create toString method in a fast way using IntelliJ: in the Code menu choose Generate.
How to use the method in the client class? Once an instance called liza is created, it can use its methods in the client class:
// Print info about Liza System.out.println(liza.toString()); // Demonstrate Liza's woofing System.out.println(liza.woofing());
In fact, method toString is exceptional which is applicable for printing object. Only this method can be uses in a reduced format like:
System.out.println(liza);
Self-assessment
Session 3 |