Java OOPS Concept

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure and organize code. In Java, OOP principles are foundational to the design and functionality of most applications. The core concepts of OOP in Java are:

Classes and Objects

Encapsulation

Inheritance

Polymorphism

Abstraction

Classes

A class is a blueprint or template for creating objects. It defines the structure (fields/variables) and behavior (methods) that the objects of the class will have.

Fields: Variables that store the state or properties of the object.

Methods: Functions that define the behavior or actions the object can perform.

Object

An object is an instance of a class. It represents a real-world entity with both state and behavior. An object is created by instantiating a class.

Encapsulation

Encapsulation is the concept of bundling data (variables) and methods that operate on the data within a single unit (class). It also restricts direct access to some of the object’s components by using access modifiers like private, public, etc.

Private fields: Keep the internal state of an object hidden.

Public methods: Provide controlled access to the internal state of the object.

Inheritance

Inheritance allows one class (child class or subclass) to inherit fields and methods from another class (parent class or superclass). This promotes code reuse and creates a natural hierarchy between classes.

Important Notes:

1. extends keyword: Used to create a subclass from a superclass.

2. The subclass inherits all non-private members of the superclass.

3. A subclass can override methods of the superclass to provide a specific implementation.

Polymorphism

Polymorphism allows you to treat objects of different classes in the same way, using a common superclass type. The term “polymorphism” means “many forms”, and it allows methods to take on different behaviors based on the objects that call them.

There are two types of polymorphism

Compile-time Polymorphism (Method Overloading): Same method name, but with different parameters.

Runtime Polymorphism (Method Overriding): Same method signature, but the behavior is defined in the subclass.

Abstraction

Abstraction is the concept of hiding the complexity of a system and showing only the essential features. It allows you to define the interface and leave the actual implementation to the subclasses or concrete classes.

Abstract Class: A class that cannot be instantiated on its own and can contain abstract methods (methods without a body).

Interface: A contract that defines methods but does not provide implementation. Classes must implement the interface methods.