Java OOP Concepts
The four pillars of Object-Oriented Programming explained concisely for Java developers.
1. Encapsulation
Meaning: Hiding the internal state and requiring all interaction to be performed through an object's methods.
In Java, this is achieved by declaring the class variables as private and providing public getter and setter methods to modify and view the values.
public class Student {
private String name; // Private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}2. Inheritance
Meaning: Deriving a new class from an existing class to inherit its properties and methods.
Java uses the extends keyword for class inheritance. It promotes code reusability.
public class User {
protected String username;
public void login() {
System.out.println("Logging in...");
}
}
// Admin inherits from User
public class Admin extends User {
public void deleteSystem() {
System.out.println("System deleted by " + username);
}
}3. Polymorphism
Meaning: The ability of an object to take on many forms. The most common use in OOP occurs when a parent class reference is used to refer to a child class object.
Polymorphism in Java is often categorized into compile-time (method overloading) and runtime (method overriding).
class Animal {
public void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Bark");
}
}
// Usage
Animal myAnimal = new Dog();
myAnimal.sound(); // Prints "Bark"4. Abstraction
Meaning: Hiding complex implementation details and showing only the essential features of the object.
This is achieved using abstract classes or interfaces.
abstract class Shape {
abstract void draw(); // No body!
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle...");
}
}