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 defined within the object class.
These methods represent different actions that the client class could be able to do with the state stored in the instance fields.
Instance methods can be created the same way as any other methods, but the instance methods do not have the static property. Here is a general syntax used to create an instance 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 state, 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 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 values of the fields 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 print 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 these created method in the client class? Once an instance called liza is created, it can use its methods in the client class using the dot notation:
// 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 used in a reduced format like:
System.out.println(liza);
Self-assessment
Session 3 |