Object Oriented Programming OOP
Why OOP?
Since people perceive the world in objects, the analysis of systems is often modeled in an object-oriented manner. But with procedural systems that only have subprograms as a means of expression, it becomes difficult to map the object-oriented design into a programming language, and a gap arises. Over time, documentation and implementation diverge; the software is then difficult to maintain and expand. It is better to think in an object-oriented way and then have an object-oriented programming language to map it.
Identity, state, behavior
The objects depicted in the software have three important properties:
- Every object has an identity.
- Every object has a state (fields).
- Every object exhibits a behavior (methods).
- These three properties have important consequences:
- the identity of the object remains the same during its life until its death and cannot change.
- the data and the program code for manipulating this data are treated as belonging together.
- In procedural systems, scenarios like the following are often found:
There is a large memory area that all subprograms can access in some way. - This is different with objects, as they logically manage their own data and monitor manipulation.
- In object-oriented software development, it is therefore about modeling in objects and then programming. Design plays a central role here; large systems are broken down and described in ever greater detail.
- In procedural systems, scenarios like the following are often found:
Creating new Objects
In Java, an object is an instance of a class. You create an object using the new keyword, followed by the class constructor. The process of creating an object involves three main steps:
- Declaration: A variable is declared with a class name to hold the reference to the object.
- Instantiation: The
newkeyword is used to create an object. - Initialization: The class constructor is called to initialize the newly created object.
ClassName objectName = new ClassName();
example: object creation
// Define a Car class
public class Car {
// Fields (properties)
String color;
int speed;
// Constructor
public Car(String color, int speed) {
this.color = color;
this.speed = speed;
}
// Method to display car information
public void displayInfo() {
System.out.println("Car color: " + color + ", Speed: " + speed);
}
// Main method to create objects
public static void main(String[] args) {
// Create an object of the Car class using the constructor
Car myCar = new Car("Red", 120);
// Accessing the object's method
myCar.displayInfo(); // Output: Car color: Red, Speed: 120
}
}
In this example:
Car myCar = new Car("Red", 120);creates an object namedmyCarof theCarclass.- The constructor
Car("Red", 120)is used to initialize thecolorandspeedfields of theCarobject.