OOPs Concepts in Java with Code Examples for Beginners

Today we will discuss, OOPs concepts in java with code examples for beginners. Object-Oriented Programming (OOP) is a programming paradigm that uses objects as the fundamental building blocks of software development. OOP is based on several core concepts that enable the organization and structuring of code in a way that models real-world entities and their interactions.

Summary for OOPs Concepts in Java with Code:

  • Classes and Objects: Basic building blocks in OOP, where classes define the structure and objects are instances of these classes.
  • Inheritance: Mechanism for creating new classes based on existing ones, promoting code reuse.
  • Polymorphism: Ability for different classes to be treated as instances of the same class through method overriding and overloading.
  • Encapsulation: Protects the data by restricting access to the internal state of the object.
  • Abstraction: Hides the complex implementation details and shows only the necessary features.
OOPs Concepts in Java with Code Examples for Beginners
OOPs Concepts in Java with Code Examples for Beginners

OOPs Concepts in Java

Here are the basic concepts of OOPs Concepts in Java for Beginners:

Objects

Objects are instances of classes and represent real-world entities. They encapsulate both data (attributes or properties) and behavior (methods or functions) related to the entity. Objects are self-contained and interact with each other through well-defined interfaces.

Classes

Classes are blueprints or templates for creating objects. They define the structure, attributes, and behaviors that objects of the class will have. A class acts as a blueprint, and objects are created from it.

// Class definition
class Car {
    String make;
    String model;
    
    // Constructor
    public Car(String make, String model) {
        this.make = make;
        this.model = model;
    }
    
    // Method
    public void start() {
        System.out.println("Starting the " + make + " " + model);
    }
}

// Creating objects
Car car1 = new Car("Toyota", "Camry");
Car car2 = new Car("Honda", "Civic");

Encapsulation

Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on that data into a single unit (a class). Access to the data is controlled through access modifiers like private, protected, and public, ensuring that data is not directly exposed but accessed through well-defined methods.

class Person {
    // Private attributes
    private String name;
    private int age;
    
    // Public getter method for name
    public String getName() {
        return name;
    }
    
    // Public setter method for name
    public void setName(String newName) {
        name = newName;
    }
    
    // Public getter method for age
    public int getAge() {
        return age;
    }
    
    // Public setter method for age
    public void setAge(int newAge) {
        age = newAge;
    }
}

public class Main {
    public static void main(String[] args) {
        Person myPerson = new Person();
        
        // Set attributes using setter methods
        myPerson.setName("John");
        myPerson.setAge(25);
        
        // Get attributes using getter methods
        System.out.println("Name: " + myPerson.getName());
        System.out.println("Age: " + myPerson.getAge());
    }
}

Inheritance

Inheritance allows one class (subclass or child class) to inherit attributes and methods from another class (superclass or parent class). It promotes code reuse and the creation of specialized classes that are based on more general ones.

class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking.");
    }
}

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables code to work with objects at a higher level of abstraction, allowing different classes to provide their own implementations of methods. Polymorphism includes method overriding and method overloading.

class Shape {
    void draw() {
        System.out.println("Drawing a shape.");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle.");
    }
}

Method Overriding

Subclasses can provide their own implementations of methods inherited from a superclass. This allows for dynamic dispatch, where the appropriate method is called based on the actual object’s type.

class Animal {
    void sound() {
        System.out.println("This animal makes a sound.");
    }
}

class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("The cat meows.");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myCat = new Cat();
        myCat.sound(); // Calls the overridden method in Cat class
    }
}

Method Overloading

Multiple methods with the same name but different parameter lists can exist within the same class. The correct method to invoke is determined at compile time based on the method signature.

class MathUtils {
    // Method with one parameter
    int add(int a) {
        return a + 10;
    }
    
    // Method with two parameters
    int add(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        MathUtils math = new MathUtils();
        
        System.out.println(math.add(5)); // Calls add(int a)
        System.out.println(math.add(5, 3)); // Calls add(int a, int b)
    }
}
OOPs Concepts in Java with Code Examples for Beginners
OOPs Concepts in Java with Code Examples for Beginners

Abstraction

Abstraction is the process of simplifying complex systems by modeling classes based on the essential properties and behaviors while hiding unnecessary details in Java. Abstract classes and interfaces are used to achieve abstraction.

abstract class Shape {
    abstract void draw();
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle.");
    }
}
  • Abstract Classes: These are classes that cannot be instantiated themselves but can be subclassed. They may contain abstract (unimplemented) methods that must be implemented by subclasses.
  • Interfaces: Interfaces define a contract that classes must adhere to. They declare method signatures that implementing classes must provide. Multiple interfaces can be implemented by a single class.

Composition

Composition is the practice of creating complex objects by combining simpler objects or components. It allows for building more extensive and flexible systems by assembling objects like building blocks.

class Engine {
    void start() {
        System.out.println("Engine started.");
    }
}

class Car {
    private Engine engine;
    
    public Car() {
        engine = new Engine();
    }
    
    void start() {
        engine.start();
        System.out.println("Car started.");
    }
}

These OOPs concepts in Java provide a framework for designing software systems that are modular, maintainable, and extensible. OOP promotes code reusability, reduces code duplication, and helps in modeling real-world systems in a natural and intuitive way. It is widely used in languages like Java, C++, Python, and more for developing applications of various sizes and complexities. Click here, if you want to free download Java pdf books for more OOPs concepts in java with code examples.

OOPs Concepts in Java with Code Examples for Beginners

Leave a Comment