Java OOP Fundamentals: A Beginner’s Roadmap
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects,” which encapsulate data and behavior. Java is one of the most widely used OOP languages. The key principles of OOP in Java include:
1. Class and Object
- Class: A blueprint for creating objects. It defines properties (fields/variables) and behaviors (methods).
- Object: An instance of a class with a unique identity and state.
Example:
class Car {
String brand;
int speed;
void display() {
System.out.println("Brand: " + brand + ", Speed: " + speed);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.brand = "Toyota";
car1.speed = 120;
car1.display();
}
}
2. Encapsulation
Encapsulation is the process of wrapping data and methods into a single unit (class) and restricting direct access to the data.
Example:
class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance;
}
}
3. Inheritance
Inheritance allows a class (child/subclass) to inherit fields and methods from another class (parent/superclass).
Example:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound();
dog.bark();
}
}
4. Polymorphism
Polymorphism allows a single method, interface, or operator to take multiple forms.
Method Overloading (Compile-time Polymorphism):
class MathOperations {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
Method Overriding (Runtime Polymorphism):
class Parent {
void show() {
System.out.println("Parent class");
}
}
class Child extends Parent {
void show() {
System.out.println("Child class");
}
}
5. Abstraction
Abstraction hides the implementation details and exposes only essential functionalities.
Using Abstract Class:
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle {
void start() {
System.out.println("Car starts with a key");
}
}
Using Interface:
interface Animal {
void sound();
}
class Cat implements Animal {
public void sound() {
System.out.println("Cat meows");
}
}
Conclusion
OOP concepts in Java provide a structured programming approach, making developing scalable and maintainable applications easier. Mastering these principles will help you write efficient Java programs.
Happy coding!
— — — — — — — —
Follow my Instagram page — Programming_Pulse for daily programming tips and insights!