Skip to main content

Java OOPs Concepts: Explained with Examples

Inheritance

Inheritance is a mechanism in which a new class is derived from an existing class. The existing class is called the parent or superclass, and the new class is called the child or subclass. The child class inherits all the properties and methods of the parent class and can also add new properties and methods of its own.


public class Animal {
    public void move() {
        System.out.println("The animal is moving");
    }
}

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

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.move(); // inherited method
        dog.bark(); // own method
    }
}
			

In the above example, the class Dog is derived from the class Animal. The Dog class inherits the move() method from the Animal class and also adds a new method bark().

Polymorphism

Polymorphism is the ability of an object to take on many forms. In Java, polymorphism is achieved through method overriding and method overloading.


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

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

public class Rectangle extends Shape {
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape shape1 = new Circle();
        Shape shape2 = new Rectangle();
        shape1.draw(); // overridden method
        shape2.draw(); // overridden method
    }
}
			

In the above example, the classes Circle and Rectangle inherit from the class Shape and override its draw() method. The Main class creates instances of the Circle and Rectangle classes and assigns them to variables of type Shape. The draw() method is called on these variables, which invokes the overridden method in the respective subclass.

Encapsulation

Encapsulation is the practice of hiding the internal details of an object from the outside world and only exposing a public interface. In Java, encapsulation is achieved through access modifiers.


public class BankAccount {
private double balance;

public void deposit(double amount) {
    if (amount > 0) {
        balance += amount;
    }
}

public void withdraw(double amount) {
    if (amount > 0 && balance >= amount) {
        balance -= amount;
    }
}

public double getBalance() {
    return balance;
}
}

public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(500);
System.out.println("Balance: " + account.getBalance()); // only public method
}
}

In the above example, the class BankAccount has a private variable balance and public methods deposit(), withdraw(), and getBalance(). The private variable can only be accessed within the class, but the public methods provide a way to interact with the object from outside. The Main class creates an instance of the BankAccount class and calls its public methods to perform operations on the object.

Abstraction

Abstraction is the process of hiding the implementation details of an object and only exposing the essential features. In Java, abstraction is achieved through abstract classes and interfaces.


public abstract class Vehicle {
protected int numWheels;

public Vehicle(int numWheels) {
    this.numWheels = numWheels;
}

public abstract void start();

public void stop() {
    System.out.println("Vehicle stopped");
}
}

public class Car extends Vehicle {
public Car() {
super(4);
}
public void start() {
    System.out.println("Car started");
}
}

public class Main {
public static void main(String[] args) {
Vehicle car = new Car();
car.start(); // abstract method
car.stop(); // inherited method
}
}

In the above example, the abstract class Vehicle defines an abstract method start() and a concrete method stop(). The Car class extends the Vehicle class and provides an implementation for the start() method. The Main class creates an instance of the Car class and assigns it to a variable of type Vehicle, which can only access the abstract and concrete methods defined in the Vehicle class.

Comments

Popular posts from this blog

a simple example for jdbc PreparedStatement

a simple example for PreparedStatement package basics.in.java.blogspot.in; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Main { private static final String USERNAME="root"; private static final String PASSWORD=""; private static final String CONN_STRING="jdbc:mysql://localhost/basicsinjavablogspot"; public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection conn=null; Statement stmt=null; ResultSet rs=null; try { conn= DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); System.out.println("database connection successful"); //stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql="select * fr...

Server-Side Pagination with React-Table and Spring Boot JPA with H2 Database

Pagination is a common technique used to split large amounts of data into smaller, more manageable chunks. With server-side pagination, data is retrieved from the server in smaller batches, reducing the amount of data transferred over the network and improving application performance. React-Table provides a wide range of built-in features such as sorting, filtering, pagination, row selection, and column resizing. These features can be easily configured and customized to fit specific requirements. For example, you can customize the sorting behavior to handle multiple sorting criteria, or you can add custom filters to the table to handle complex data filtering scenarios. Additionally, React-Table provides a flexible API that allows developers to extend its functionality with custom hooks, plugins, and components. This means that you can easily add custom functionality to the table, such as exporting data to CSV or integrating with external data sources. In terms of styl...