Project
Object-Oriented Programming (OOP) is a popular programming paradigm that is widely used in Java programming. OOP focuses on the use of classes and objects, and it has several concepts that are referred to as "Oops Concepts" in Java. Some of the main Oops Concepts in Java with examples are:
- Encapsulation - This is the concept of wrapping data and methods into a single unit, which is known as a class. This helps in hiding the implementation details of the class from the user. For example:
In the above example, the data members accountNumber and balance are private, which means they can only be accessed within the class. The methods getAccountNumber(), getBalance(), deposit(), and withdraw() are public, which means they can be accessed by other classes.
- Inheritance - This is the concept of creating a new class from an existing class. The new class, also known as the subclass, inherits the properties and methods of the existing class, which is known as the superclass. For example:
public class Animal {public void eat() {System.out.println("Animal is eating");}}public class Dog extends Animal {public void bark() {System.out.println("Dog is barking");}}public class Main {public static void main(String[] args) {Dog dog = new Dog();dog.eat();dog.bark();}}
In the above example, the
Dogclass extends theAnimalclass and inherits itseat()method. TheDogclass also has a new methodbark()that is not present in theAnimalclass.
- Polymorphism - This is the concept of having many forms. It allows objects of different classes to be treated as if they belong to the same class, which is achieved through method overloading and method overriding. For example:
public class Shape {public void draw() {System.out.println("Drawing a shape");}}public class Circle extends Shape {@Overridepublic void draw() {System.out.println("Drawing a circle");}}public class Rectangle extends Shape {@Overridepublic 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();shape2.draw();}}
In the above example, the
CircleandRectangleclasses override thedraw()method of theShapeclass, which allows them to draw their own specific shape. TheMainclass creates objects of theCircleandRectangleclasses and assigns them to variables of typeShape. This allows thedraw()method to be called on each of these objects using the same variable, demonstrating polymorphism
- Abstraction - This is the concept of hiding the implementation details of a class and only exposing its interface. This is achieved through abstract classes and interfaces. For example:
public abstract class Vehicle {public abstract void start();public abstract void stop();}public class Car extends Vehicle {@Overridepublic void start() {System.out.println("