Basics of OOP — Object Oriented Programming

Consider a complex piece of machinery, maybe a car. The car is made up of different components. The different components are then connected to each other where the output of one becomes the input to the other.  What would happen if the car was built as a single huge machine rather than as connected components?

The whole thing would become extremely complicated. It would be difficult to make and even more difficult to repair if something goes wrong.  Object Oriented Programming is the process by which we bring this concept of component based system into the realm of programming.

Let us look up the steps involved in creating the car and also its analog in the software development process.
1. We create a design of the car on paper, list the parts and their functionalities. This is the class, its variables and the methods.
2. Get the respective components and fix them on their respective positions. This is the constructor of the class.
3. The car is the object.

Let us try and build a class to illustrate this process just now.

public class Book {
private String name,subject;
private int price;

public Book(String name, String subject, int price) {
this.name = name;
this.subject = subject;
this.price = price;
}

@Override
public String toString() {
return "Book{" + "name=" + name + ", subject=" + subject + ", price=" + price + '}';
}

public static void main(String[] args) {
Book book=new Book("The Recursion Sutras", "Recursion in Java", 200);
System.out.println(book);
}
}

Continuing our analogies. name, subject and price are the parts, public Book is the constructor, and book is the object. The toString method gives a string representation of an object of the class.

The output is:

Book{name=The Recursion Sutras, subject=Recursion in Java, price=200}

Leave a Reply