Adding Attributes and Methods
Estimated time to read: 1 minute
Overview¶
Attributes must be added inside the class block and outside all method blocks.
They must be given a data type. In the example below, the types int
and boolean
are used.
Accessibility of Objects within Classes¶
Attributes and Methods within a class have accessibility tied to them, meaning that there are restrictions on who may invoke a method or access an attribute.
Accessibility is part of a member of a class, a member could be an attribute, a sub-class or a method.
Access Modifier | Description |
---|---|
Public | Allows access by aall other objects in the system |
Private | Allows access only within the same class definition.(No other class can touch the data) |
Accessibility Example¶
package io.entityfour;
public class Car {
private int speed;
private int gasoline;
private boolean engineState;
public void setSpeed(int newSpeed){
speed = newSpeed;
}
public int getSpeed(){
return speed;
}
}
Methods must be defined with their name, signature and return type. If a method returns nothing, it must be declared to return void. The above example, the data is private to the class itself but there are public methods that can be called upon to get or set data.