Object methods

Figure 228. Object methods Slide presentation Create comment in forum
Change an object's state.

Example: Scale a rectangle.

Get dependent values

Example: Calculate a rectangle's perimeter.

Combined

Scale a rectangle and calculate its new perimeter.


Figure 229. Scaling a rectangle Slide presentation Create comment in forum
Scaling a rectangle

Figure 230. Scaling method implementation Slide presentation Create comment in forum
public class Rectangle {
    int width, height;
    boolean hasSolidBorder;

    public void scale (int factor) {
        width *= factor;
        height *= factor;
    }
}
Scaling method implementation

Figure 231. Scaling method signature Slide presentation Create comment in forum
void  scale (int factor ) {
...}

No value is being returned to caller.

A single value of type int is being provided as method argument.


Figure 232. Using scale(...) method Slide presentation Create comment in forum
Rectangle r = new Rectangle();
r.width = 33;
r.height = 22;

r.scale(2);

System.out.println("width=" + r.width);
System.out.println("height=" + r.height);
width=66
height=44

Figure 233. Method definition syntax Slide presentation Create comment in forum
public  void  scale (int factor ) { 
   width *= factor; 
   height *= factor;
}
[access modifier]  return_type  methodName  ([arguments] ) {
   [statement(s)] 
}

Optional access control modifier either of public, protected or private.

The method's return type either of:

void

The method will not return a value on completion.

A data type e.g. int, double, ...

The method will return a value of the given type to its caller.

The method's name.

Arguments being required for execution.

Start of method's body.

The method's implementation.


Figure 234. A rectangle's perimeter Slide presentation Create comment in forum
A rectangle's perimeter

Figure 235. Get perimeter implementation Slide presentation Create comment in forum
public class Rectangle {
    int width, height;
    boolean hasSolidBorder;

    public void scale (int factor) { ... }

    public int getPerimeter() {
        return 2 * (width + height);
    }
}
Get perimeter implementation

Figure 236. Using Rectangle.getPerimeter() Slide presentation Create comment in forum
Rectangle r = new Rectangle();

r.width = 33;
r.height = 22;

System.out.println("Perimeter=" + r.getPerimeter());
Perimeter=110