Internal State

The internal state of an object represents the values of its attributes or properties at a given point in time.

To understand better, let’s consider a simple object representing a car.

Photo by Pixabay on Pexels.com

The internal state of the car object could include attributes such as speed, fuel level, and engine temperature. These attributes store the specific values associated with the car object, which can vary over time as the car operates modifying its internal state.

In Java a car object is represented like this.

public class Car {
private int speed;
private double fuelLevel;
private double engineTemperature;
public Car(int initialSpeed, double initialFuelLevel, double initialEngineTemperature) {
this.speed = initialSpeed;
this.fuelLevel = initialFuelLevel;
this.engineTemperature = initialEngineTemperature;
}
// Getters and Setters for the attributes
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public double getFuelLevel() {
return fuelLevel;
}
public void setFuelLevel(double fuelLevel) {
this.fuelLevel = fuelLevel;
}
public double getEngineTemperature() {
return engineTemperature;
}
public void setEngineTemperature(double engineTemperature) {
this.engineTemperature = engineTemperature;
}
// Other methods and functionalities of the Car class
}
view raw Car.java hosted with ❤ by GitHub

In this Car class, the attributes “speed,” “fuelLevel,” and “engineTemperature” represent the internal state of the car. These attributes store information about the current speed of the car, the fuel level, and the engine temperature, respectively.

The Car class also includes “getters” and “setters” These methods allow access and modify the values of these attributes, allowing obtaining and setting the speed, fuel level, and engine temperature from other parts of the code.

When we do a modification of one of these attribute values we say that we Modify the internal state of an object, this means changing the values of its attributes or properties. In the case of the car object, updating its internal state could involve increasing or decreasing the speed, refueling, or adjusting the engine temperature.

In Java and object-oriented programming OOP, the objects encapsulate their internal state and provide methods or operations to interact with that state. This encapsulation helps ensure data integrity and allows for controlled access to an object’s internal data.

In Java, encapsulation is achieved by using access modifiers on the attributes, and accessors and mutators getters and setters methods of a class.

Final Notes! In addition to these attributes and methods, the Car class can have other functionalities and related methods, such as methods to accelerate or brake the car, check the fuel level, and display information about the car, among others.

Happy Learning!

Leave a comment