Object-Oriented Programming in Java
In Java, object-oriented programming (OOP) is a programming paradigm that organizes code around objects that can contain data and code. It provides a structured and modular approach to building software, making it easier to manage and maintain.
At the core of OOP in Java are four key concepts: classes, objects, inheritance, and polymorphism.
Classes
A class is a blueprint or template for creating objects. It defines the properties (variables) and behaviors (methods) that objects of that class can have. For example, let's create a Car
class:
TEXT/X-JAVA
1// Define a Car class
2public class Car {
3 // Instance variables
4 String make;
5 String model;
6
7 // Constructor
8 public Car(String make, String model) {
9 this.make = make;
10 this.model = model;
11 }
12
13 // Methods
14 // ...
15}
xxxxxxxxxx
35
}
class Main {
public static void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Tesla", "Model S");
// Call the accelerate method on the car object
myCar.accelerate(100);
// Call the brake method on the car object
myCar.brake();
}
}
// Define a Car class
class Car {
// Instance variables
String make;
String model;
// Constructor
public Car(String make, String model) {
this.make = make;
this.model = model;
}
// Method to accelerate
public void accelerate(int speed) {
System.out.println(make + " " + model + " is accelerating at " + speed + " mph.");
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment