Object methods
- Get (dependent) values
-
Example: Calculate a rectangle's area.
- Change an object's state.
-
Example: Scale a rectangle.
- Combined
-
Scale a rectangle and calculate its new perimeter.
public class Rectangle {
int width, height;
int getArea() {
return width * height;
}
} |
public static void main(String[] args) {
Rectangle r = new Rectangle();
r.width = 20;
r.height = 30;
int area = r.getArea();
System.out.println(
"Area of rectangle is: " + area);
} |
Area of rectangle is: 600
public class Rectangle {
int width, height;
int getArea() {...}
public void scale (int factor) {
width *= factor;
height *= factor;
}
} |
Rectangle r = new Rectangle();
r.width = 20;
r.height = 30;
System.out.println("Area before scaling: "
+ r.getArea());
r.scale(2);
System.out.println("Area after scaling: "
+ r.getArea()); |
Area before scaling: 600 Area after scaling: 2400
|
width=66 height=44 |
public ❶ void ❷ scale❸ (int factor ❹) { ❺ width *= factor; ❻ height *= factor; } |
[access modifier] ❶ return_type ❷ methodName ❸ ([arguments] ❹) {❺ [statement(s)] ❻ } |
|
Optional access control
modifier either of |
|
|
The method's return type either of:
|
|
|
The method's name. |
|
|
Arguments being required for execution. |
|
|
Start of method's body. |
|
|
The method's implementation. |
|
|
|
Perimeter=110 |
No. 89
Compile time error
|
Q: |
Try to compile the following snippet: You'll encounter a “Missing return statement” error. What's wrong here? On contrary the following code compiles and executes perfectly well: |
|
A: |
The compiler effectively complains about a missing
On the other hand the return statement in
Albeit executing well the above code is flawed: Calling e.g.
|
No. 90
An Address class
|
Q: |
Consider the following UK postal address sample code and desired execution result:
Create an appropriate |
||||
|
A: |
Our Address class requires six attributes of type String and
a |
