What is OOP?

OOP stands for Object-Oriented Programming. It is about writing code based on the concept of “objects”. An object has properties (attributes) and behaviours (methods). For example: the properties of a car include make, model, colour, etc. while the behaviours of a car include drive, brake, horn etc.

In Java, properties are called attributes and behaviours are called methods (or functions).

Object vs Class

A Class is a blueprint or a template for creating an object.

An object is an instance of a class. For example, in real life, a car is an object.

Define a Java Class

Define

public class Car {
	private String make;
	private String model;
	private String colour;
	private int noOfWheels;
	private String brakeType;
	
	public Car(String make, String model, String colour, int noOfWheels, String brakeType) {
		super();
		this.make = make;
		this.model = model;
		this.colour = colour;
		this.noOfWheels = noOfWheels;
		this.brakeType = brakeType;
	}

	public void drive() {
		System.out.println("Drive on " + noOfWheels + " wheels");
	}

	public void brake() {
		System.out.println("Brake using " + brakeType);
	}
	
	public String summarise() {
		String summary = "Hello! I am a " + colour + " " + make + " " + model + " car. I drive on " + noOfWheels + " wheels and brake using " + brakeType + ".";  
		return summary;
	}
}

Create and use an object

public class TestCar {

	public static void main(String[] args) {
		Car car = new Car("Lexus", "RX 450h+ F SPORT", "Black", 4, "ABS");
		car.drive();
		car.brake();
		System.out.println(car.summarise());
	}

}

Below is the result from executing the main method of the TestCar class above:

Principles of Object Oriented Programming

The four main principles of OOP are: