Java OOP's Concept - A Complete Guide with Examples

Java OOP's Concept

    Introduction to Object-Oriented Programming (OOP)

    Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure software programs. Java is one of the most popular languages that follows OOP principles.

    Example:

    class Dog {

       String name;

         void bark() {

       System.out.println("Woof!");

       }

    }

    Here, Dog is a class and can be used to create dog objects.

    Basic Principles of OOP

    OOP revolves around 4 main pillars:



    •  Encapsulation
    •  Inheritance
    •  Polymorphism
    •  Abstraction

    Each principle helps create modular, maintainable, and reusable code.

    Class and Object in Java

    •  Class: A blueprint for objects.
    •  Object: An instance of a class.

    Example:

    class Car {

      String color;

      int speed;

       void display() {

          System.out.println("Color: " + color + ", Speed: " + speed);

        }

    }

    public class Main {

      public static void main(String[] args) {

          Car myCar = new Car();

          myCar.color = "Red";

          myCar.speed = 100;

          myCar.display();

       }

    }

    Encapsulation in Java

    Encapsulation hides the internal state of objects and allows controlled access via methods.

    Example:

    class Employee {

       private String name;

          public void setName(String name) {

       this.name = name;

    }

         public String getName() {

         return name;

       }

    }

    Inheritance in Java

    Inheritance allows one class to inherit fields and methods from another.

    Example:

     class Animal {

        void eat() {

            System.out.println("This animal eats food.");

        }

    }

       class Dog extends Animal {

          void bark() {

           System.out.println("The dog barks.");

        }

    }

    Polymorphism in Java

    •  Compile-time (method overloading)
    •  Runtime (method overriding)

    Example of Runtime Polymorphism:

      class Animal {

         void sound() {

            System.out.println("Animal sound");

       }

    }

    class Cat extends Animal {

        void sound() {

            System.out.println("Meow");

        }

    }

    Abstraction in Java

    •  Abstraction hides complexity by showing only essential features.

    Example:

    abstract class Shape {

       abstract void draw();

    }

       class Circle extends Shape {

         void draw() {

             System.out.println("Drawing Circle");

        }

    }

    Constructors in Java

    Constructors initialize new objects.

    Example:

    class Student {

      String name;

      int age;

          Student(String name, int age) {

           this.name = name;

           this.age = age;

       }

    }

    Method Overloading

    Multiple methods with the same name but different parameters.

    Example:

    class Calculator {

      int add(int a, int b) {

        return a + b;

    }

    double add(double a, double b) {

          return a + b;

       }

    }

    Method Overriding

    Subclass provides a specific implementation of a superclass method.

    Example:

    class Animal {

       void sound() {

           System.out.println("Animal sound");

        }

    }

    class Dog extends Animal {

       void sound() {

           System.out.println("Dog barks");

        }

    }

    Access Modifiers

    •  private: Accessible within class
    •  default: Accessible within package
    •  protected: Accessible within package and subclasses
    •  public: Accessible everywhere

    The 'this' Keyword

    this refers to the current object.

    Example:

    class Car {

       String color;

         Car(String color) {

         this.color = color;

       }

    }

    The 'super' Keyword

    Used to refer parent class methods and constructors.

    Example:

     class Animal {

       void sound() {

          System.out.println("Animal sound");

       }

    }

    class Dog extends Animal {

       void sound() {

          super.sound();

          System.out.println("Dog barks");

       }

    }

    Final Keyword

    Used to declare constants, prevent overriding and inheritance.

    Example:

    final class Animal {}

    final int MAX = 100;

    Static Keyword

    Belongs to the class rather than instances.

    Example:

    class MathUtil {

       static int square(int x) {

         return x * x;

       }

    }

    Abstract Classes

    Cannot be instantiated but can have abstract and non-abstract methods.

    Example:

    abstract class Animal {

       abstract void sound();

    }

    class Dog extends Animal {

       void sound() {

          System.out.println("Dog barks");

        }

    }

    Interfaces

    Interface contains abstract methods that must be implemented.

    Example:

    interface Animal {

        void sound();

    }

    class Dog implements Animal {

       public void sound() {

         System.out.println("Dog barks");

       }

    }

    Packages in Java

    Packages group related classes.

    Example:

    package mypackage;

    public class MyClass {}

    Exception Handling in OOP

    Handle runtime errors gracefully.

    Example:

    try {

        int result = 10 / 0;

    } catch (ArithmeticException e) {

        System.out.println("Cannot divide by zero");

    }

    Composition vs Inheritance

    •  Inheritance: "is-a" relationship
    •  Composition: "has-a" relationship

    Example:

    class Engine {}

    class Car {

       Engine engine; // Composition

    }

    Nested and Inner Classes

    Classes within other classes.

    Example:

    class Outer {

       class Inner {

           void display() {

           System.out.println("Inner class");

         }

      }

    }

    Object Class

    Every class in Java inherits from Object class.

    Example:

    class MyClass {

        public String toString() {

            return "MyClass Object";

        }

    }

    Java Collections and OOP

    Collections like ArrayList use OOP principles.

    Example:

    import java.util.*;

    List<String> list = new ArrayList<>();

    list.add("Java");

    Design Patterns and OOP

    Design patterns solve common software design problems.

    Example (Singleton):

    class Singleton {

       private static Singleton instance;

       private Singleton() {}

       public static Singleton getInstance() {

         if (instance == null) {

            instance = new Singleton();

         }

         return instance;

       }

    }

    Conclusion

    Java's OOP concepts provide a robust framework for building scalable, maintainable, and efficient applications. Understanding classes, objects, inheritance, polymorphism, abstraction, and encapsulation is essential for any Java developer.


    Also Read:

    Post a Comment

    0 Comments