01 Java - 4 Pillars of OOPs

OOPS Overview

  • OOPS means Object-Oriented Programming.

  • Here Object means real word entity like Car, Bike, ATM ..etc.

  • Any real world entity has 2 things. One is behaviour (functionality) and other is properties.

Procedural ProgrammingOOPS
Program is divided into parts called functionsProgram is divided into Objects
Does not provide proper way to hide data, gives importance to function and data moves freelyObjects provide data hiding, gives important to data.
Overloading is not possibleOverloading is possible
Inheritance is not possibleInheritance is possible
Code reusability does not presentCode reusability is present
Examples: Pascal, C, FORTRAN etcExamples: Java, C#, Python, C++ etc

Objects and Classes

Object has 2 things

  • Properties or state

  • Behavior or Function

Example:

  1. Dog is an Object because it has

    • Properties like: Age, Breed, Color etc.

    • Behaviors like Bark, Sleep, Eat etc.

  2. Car is an Object because it has:

    • Properties like: Color, Type, Brand, Weight etc.

    • Behaviors like: Apply Break, Drive, Increase Speed etc.

Classs

  • To create an Object , a class is required

  • So, Class provides the template or Blueprint from which object can be created.

  • From one Class, we can create multiple objects.

  • To create a class, use the keyword class:

class Student{
    // Data Variables
    int age;
    String address;

    // Data Methods
    updateAddress(){
        //...
    }

    getAge(){
        return age;
    }
}
Student engStudent = new Student();
Student mbaStudent = new Student();

4 Pillars

1st Pillar of OOPS - Data Abstraction

  • It hides the internal implementation and shows only essential fucntionality to the user.

  • It can be achieved through Interface and abstract classes

Examples:

  1. Car - We only shown the BREAK pedal, and if we press it, Car speed will reduce. But HOW?? That is ABSTRACTED to us.

  2. Cellphone - How call is made that is Abstracted to us.

Advantages of abstraction

  • Increase scurity and confidentiality
interface Car{
    public applyBreak();
    public pressAccelerator();
    public pressHorn();
}
class CarImpl implement Car{
    public applyBreak(){
        //Core Logic of applying the breaks
    }
}

2nd Pillar of OOPS - Data Encapsulation

  • Encapsulation bundles the data and the code working on that data in a single unit.

  • Also known as DATA - HIDING

  • Steps to achieve encapsulation

    • Declare all varaibles of a class as private.

    • Provide a Public Getters and Setters to modifiy and view the value of the variables.

Advantages

  • Loosely coupled code

  • Better access control and security

  • Increased flexibility: Variables can be made read-only or write-only

Analogy

Imagine a human being as a class in programming. Each piece of information stored in our brain can be likened to a data variable within that class. We choose to reveal these data variables only under specific circumstances. For instance, we may willingly share our name with others, but we keep sensitive information like passwords private and inaccessible to outsiders.

3rd Pillar of OOPS - Inheritance

  • Capability of a class to inherit properties from their Parent class

  • It can inherit both functions and variables, so we do not have to have write them again in child classes.

  • Can be achieved using extends keyword or through interface.

  • Types of Inheritance

    • Single Inheritance

    • Multilevel inheritance

    • Hierarchical Inheritance

    • Mulitple Inheritance - through interface we can resolve the diamond problem

Advantages of Inheritance

  • Code reusability

  • We can achieve Polymorphism using Inheritance.

In Java, multiple inheritance isn't feasible due to potential ambiguity when two parent classes feature methods with identical names, such as "getEngine." This creates a dilemma for the child class regarding which parent class's method to invoke. Hence java doesn't support multiple inheritance.

4th Pillar of OOPS - Polymorphism

  • Poly means Many and Morphism means Form.

  • A same method, behaves differently in different situation.

  • Example:

    • A person can be father, husband, employee etc.

    • Water can be liquid, solid and Gas etc.

  • Types of Polymorphism

    • Compile Time / Static Polymorphism / Method Overloading

    • Run Time / Dynamic Polymorphism / Method Overriding

// Static Polymorphism

// Correct Method Overloading
class Sum{
    int doSum(int a, int b){
        //...
    }

    int doSum(String a, String b){
        //...
    }

    int doSum(int a, int b, int c){
        //...
    }
}

// Wrong 
class Sum{
    int doSum(int a, int b){
        //...
    }

    String doSum(int a, int b){
        //...
    }
}

//Compiler will be confused about which method to call
//it cannot differentiate based on return type
// Dynamic Polymorphism

class A{
    getEngine(arg1 ,arg2){
        //...logic of A
    }
}

class B extends A{
    getEngine(arg1 ,arg2){
        //...logic of B
    }
}

B obj = new B();
B.getEngine(); // This invokes the method of class B rather than class A

A obj = new A();
A.getEngine(); // This invokes the method of Class A

//This calling of getEngine at runtime.
//If B doesn't have getEngine then it will call the method of A
//If B has method then it overrides the method of A at runtime.

Objects Relationships

  • Is-a Relationship

    • Achieved through inheritance

    • Example: DOG is-a Animal

    • Inheritance form an is-a relation between its parent child classes.

  • Has-a Relationship

    • Whenever, an Object is used in Other Class, it's called HAS-A relationship.

    • Relationship could be one-one, one-many, many to many.

    • Example:

      • School has Students,

      • Bike has Engine,

      • School has Classes

    • Association: relationship between 2 different Objects.

      • Aggregation (Weak Relationship): Both Objects can survive individually, means ending of one object will not end other object.

      • Composition (Strong Relationship): Ending of One object will end another object.

Aggregation example: We have a school object which has a list of student objects. If there are 100 students and we destroy 98 student objects, the School object still exists without any issues. Similarly, if we destroy 1 school object, student objects still exist and they may enroll in another school. Hence, both objects can exist independently without any issues; therefore, it's a weak relation.

//Aggregation 

class School{
    List<Student> students;
}

class Student{
    //...
}

Composition example: We have 2 classes: School and Room. The School class contains a list of rooms. Rooms are created only after the school object is created. Therefore, if we destroy the school object, the room objects also get destroyed. This strong relationship indicates composition. If one object is created solely for the purpose of another object, then these two objects have a strong relationship.

//Compostiion 

class School{
    List<Room> room;
}

class Room{
    //...
}