State & Behavior
An object has state and behavior.
State
The state of an object (also known as its properties or attributes) refers to its essential and distinctive characteristics.
A class defines the attributes of its objects using data fields (instance variables). The state of an object is represented by the value of these data fields at any given time.
For instance, a Circle
class may have a data field called radius
, which represents the characteristic property of a circle.
public class Circle {
private double radius;
public Circle() { radius = 1; }
public void setRadius(double r) { radius = r; }
public double getRadius() { return radius; }
public double getArea() { return Math.PI * Math.pow(radius, 2); }
}
An instance of the Circle
class, such as a circle
object with a radius of 1
cm, has its own state. If we modify the radius of this circle to a new value, we are effectively changing its state.
Circle c1 = new Circle();
c1.setRadius(3);
Behavior
The behavior of an object refers to the set of operations or responsibilities it must fulfill.
This includes the responsibility to provide and modify state information when requested by other objects or services, known as clients. The behavior of an object is determined by the instance method that implements this behavior. Invoking a method on an object means requesting the object to fulfill a particular behavior or act.
For example, you can request a circle object to provide its state information by calling the getRadius()
method, which is declared and implemented in the Circle
class.