Here's a detailed explanation of OOP (Object-Oriented Programming) concepts in Java
with examples.
1. Classes and Objects
In Java, a class is a blueprint or template that defines the properties and behavior of an
object. An object is an instance of a class, and has its own set of attributes (data) and
methods (functions).
// Class definition
public class Car {
String color;
int speed;
void accelerate() {
speed++;
}
}
// Object creation
Car myCar = new Car();
myCar.color = "Red";
myCar.speed = 60;
myCar.accelerate();
System.out.println("Car color: " + myCar.color);
System.out.println("Car speed: " + myCar.speed);
2. Inheritance
Inheritance allows one class to inherit the properties and behavior of another class. The
child class inherits all the fields and methods of the parent class and can also add new
fields and methods or override the ones inherited from the parent class.
Java
// Parent class
public class Animal {
void eat() {
System.out.println("Eating...");
}
}
// Child class
public class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
// Usage
Dog myDog = new Dog();
myDog.eat(); // Inherited from Animal
myDog.bark(); // Specific to Dog
3. Polymorphism
Polymorphism is the ability of an object to take on multiple forms. This can be achieved
through method overriding or method overloading.
Method Overriding
Java
// Parent class
public class Shape {
void draw() {
System.out.println("Drawing a shape...");
}
}
// Child class
public class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle...");
}
}
// Usage
Shape myShape = new Circle();
myShape.draw(); // Output: Drawing a circle...
Method Overloading
Java
public class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
// Usage
Calculator calc = new Calculator();
System.out.println(calc.add(1, 2)); // Output: 3
System.out.println(calc.add(1.5, 2.5)); // Output: 4.0
System.out.println(calc.add(1, 2, 3)); // Output: 6
4. Encapsulation
Encapsulation is the concept of hiding the implementation details of an object from the
outside world and only exposing the necessary information through public methods.
public class BankAccount {
private double balance;
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
}
}
public double getBalance() {
return balance;
}
}
// Usage
BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(500);
System.out.println("Account balance: " + account.getBalance());
5. Abstraction
Abstraction is the concept of showing only the necessary information to the outside
world while hiding the implementation details.
Java
public abstract class PaymentGateway {
public abstract void processPayment(double amount);
}
public class CreditCardPayment extends PaymentGateway {
@Override
public void processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount);
}
}
public class PayPalPayment extends PaymentGateway {
@Override
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
}
}
// Usage
PaymentGateway paymentGateway = new CreditCardPayment();
paymentGateway.processPayment(100);
paymentGateway = new PayPalPayment();
paymentGateway.processPayment(100);
6. Interfaces
Interfaces define a contract that must be implemented by any class that implements it.
They can contain method signatures and constant variables.
public interface Printable {
void print();
}
public class Document implements Printable {
@Override
public void print() {
System.out.println("Printing a document...");
}
}
// Usage
Printable printable = new Document();
printable.print();
7. Composition
Composition is the concept of creating objects from other objects.
Java
public class Engine {
void start() {
System.out.println("Engine started...");
}
}
public class Car {
private Engine engine;
public Car() {
engine = new Engine();
}
void startCar() {
engine.start();
}
}
// Usage
Car car = new Car();
car.startCar();
These are the main OOP concepts in Java. Let me know if you have any specific
questions about any of these concepts.
Access Modifiers
In Java, access modifiers determine the accessibility of a class, method, or field. Here are
the four main access modifiers:
1. public: The class, method, or field can be accessed from anywhere.
2. private: The class, method, or field can only be accessed within the same class.
3. protected: The class, method, or field can be accessed within the same class and
its subclasses.
4. default (no modifier): The class, method, or field can be accessed within the same
package.
public class MyClass {
public int publicField;
private int privateField;
protected int protectedField;
int defaultField; // default access modifier
}
Constructors
Constructors are special methods that are used to initialize objects when they are
created
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// Usage
Person person = new Person("John", 30);
Static Members
Static members belong to the class rather than instances of the class.
public class MathUtils {
public static final double PI = 3.14159;
public static int add(int a, int b) {
return a + b;
}
}
// Usage
System.out.println(MathUtils.PI);
System.out.println(MathUtils.add(2, 3));
Final Keyword
The final keyword can be used to restrict the user from subclassing a class, overriding a
method, or reassigning a variable.
public final class FinalClass {
// cannot be subclassed
}
public class MyClass {
public final void finalMethod() {
// cannot be overridden
}
public final int FINAL_FIELD = 10; // cannot be reassigned
}
Enum
Enum is a special type of class used to represent a fixed set of constants.
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
// Usage
Day day = Day.MONDAY;
System.out.println(day);