Object-Oriented Programming is a programming paradigm based on the concept of "objects", which can contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods). Java is a popular object-oriented programming language, and it supports key OOP concepts such as classes, objects, inheritance, encapsulation, and polymorphism.
A class is a blueprint for creating objects. Objects are instances of classes. Below is an example of a class and its object in Java:
public class Car {
String brand;
String model;
int year;
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
public void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
// Creating an object of Car class
Car myCar = new Car("Toyota", "Camry", 2022);
myCar.displayDetails();
Inheritance allows a class to inherit properties and behaviors from another class. Below is an example demonstrating inheritance in Java:
public class Animal {
String name;
public void makeSound() {
System.out.println("Some sound");
}
}
public class Dog extends Animal {
public void makeSound() {
System.out.println("Bark");
}
}
// Creating an object of Dog class
Dog myDog = new Dog();
myDog.makeSound();
Encapsulation is the bundling of data (attributes) and methods that operate on the data into a single unit (class). Access to the data and methods is restricted by using access modifiers. Below is an example illustrating encapsulation in Java:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
// Creating an object of Person class
Person person = new Person("John", 30);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
Polymorphism allows methods to be invoked by multiple classes in different ways. It is achieved through method overriding and method overloading. Below is an example showcasing polymorphism in Java:
public class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
// Polymorphism
Animal myDog = new Dog();
myDog.makeSound(); // Output: "Bark"