Java OOPS Concepts

Class, Object, Encapsulation, Abstraction, Polymorphism & Inheritance

Prepared by SriDattaVihas

1. Class

  • A class is a combination of data members and member functions.
  • It is a user-defined data type.
  • Without object creation, memory is not created for the class's instance data.
  • A class is a logical entity that contains logic.
  • A class is used to declare/define logic.
  • A class is a blueprint, similar to a civil engineer's house blueprint.
  • Based on one blueprint, multiple houses can be created, but each house requires its own physical place.

Example

class Sample {

    // define data members
    // variables / constants

    // methods
    // blocks
}
Simple definition: A class describes the structure and behavior that its objects will have.

2. Object

  • Anything existing as a real-world entity can be represented as an object.
  • An object is a physical entity.
  • An object is an instance of a class.
  • Without a class, there is no concept of an object in this model.
  • Examples include a pen, laptop, mobile, bed, keyboard, mouse and chair.
  • Objects can be created multiple times according to requirements.
  • An object allocates memory when it is created.
  • In Java, Object is the root class for Java classes.
  • The Object class is in the java.lang package, which is implicitly imported.

Three Properties of an Object

State

Describes the data members of the object.

Behavior

Represents methods/functions.

Identity

The identity/name by which the object is identified.

Example: Dog

  • State: color, name, breed
  • Behavior: wagging the tail, barking, eating

Ways to Create an Object

The source lists several ways:

new keyword newInstance() clone() Factory method Deserialization

3. Class vs Object

Class
Logical Entity / Blueprint
Object
Physical Entity / Instance
ClassObject
Logical entityPhysical entity
Used to declare/define logicRepresents the actual instance
Acts as a blueprintCreated from the blueprint
One class can be used to create multiple objectsEach object requires its own memory
House analogy: A civil engineer's blueprint can be used to create multiple houses. The blueprint corresponds to the class, while each actual house corresponds to an object.

4. OOPS Concepts Overview

ConceptDescription / Association in the Notes
ClassLogical entity
ObjectPhysical entity
EncapsulationSecurity / data hiding
AbstractionGeneralization
PolymorphismExtensibility
InheritanceCode reusability / is-a
CompositionHas-a
InterfaceStandardization
AssociationWhole-part
AggregationPart-of
Object Life Time

5. Encapsulation

Encapsulation in Java is the mechanism of wrapping data (variables) and the code acting on that data (methods) together as a single unit.

The source describes encapsulation as hiding the variables of a class from other classes and accessing them through methods. It is therefore also known as data hiding.

Implementation in Java

  1. Private Variables: Making class variables private prevents direct access from outside the class and hides internal state.
  2. Public Methods: Public methods, commonly getters and setters, provide controlled access and can enforce rules for reading or modifying data.

Key Features

Hiding Data

Internal state is hidden from the outside world.

Access Control

Getter and setter methods provide controlled access and can perform validation or transformation.

Flexibility

Internal implementation can change without affecting external code when public methods remain consistent.

Benefits

  • Control over Data: Validation can be added to getters and setters.
  • Flexibility: Internal workings can change without affecting users of the public interface.
  • Security: Private fields prevent unintended or unauthorized changes to state.

Encapsulation Example

public class EncapsulationDemo {
    private Integer empId;
    private String empName;
    private Double salary;

    public Integer getEmpId() {
        return empId;
    }

    public void setEmpId(Integer empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public void display() {
        System.out.println("Emp Id " + empId);
        System.out.println("Emp Name " + empName);
        System.out.println("Emp Salary " + salary);
    }

    public EncapsulationDemo() {
        super();
    }

    public EncapsulationDemo(
            Integer empId, String empName, Double salary) {
        super();
        this.empId = empId;
        this.empName = empName;
        this.salary = salary;
    }
}
public class EncapsulationDemoImpl {
    public static void main(String[] args) {
        EncapsulationDemo demo =
            new EncapsulationDemo(12, "Sree", 12000.45d);
        demo.display();
    }
}
Summary from the notes: encapsulation uses access modifiers such as private and public to control how class data is accessed and modified while hiding implementation details.

6. Abstraction

Abstraction is a core OOP concept that focuses on the essential characteristics of an object while hiding unnecessary implementation details.

The source defines it simply as hiding the inner details and providing necessary information.

Real-world Example: TV Remote

The TV remote is used as an example of abstraction. The user interacts with the external interface (keys) and knows which key performs which function, without needing to know the internal implementation.

Java Example

abstract class Shape {
    public abstract void draw();
}

public class Test {
    public static void main(String[] args) {
        Circle circle = new Circle();
        // invoking abstract method
        circle.draw();
    }
}

class Circle extends Shape {
    // implementing functionality
    // of the abstract method
    public void draw() {
        System.out.println("Circle!");
    }
}

7. Polymorphism

Polymorphism is described as one of the four fundamental OOP principles. The notes describe it as one interface with multiple definitions.

Polymorphism allows objects to be treated as instances of a parent class and enables a single action to behave differently depending on the object type.

Poly
Many
+
Morphism
Forms
Many Forms

Types of Polymorphism

Compile-Time Polymorphism

Also called static binding / early binding.

Method execution decided at compile time.

Example: method overloading.

Runtime Polymorphism

Also called dynamic binding / late binding.

Method execution decided at runtime.

Example: method overriding.

Java examples listed in the notes: Different wait() methods in Object class, different sleep() methods in Thread class, and a real-time Person example.

8. Method Overloading

If a class has multiple methods with the same name but different parameters, it is called method overloading.

Overloading can differ by

  • Number of parameters.
  • Data types of parameters.
  • Order of parameters.
  • It does not depend on the return type.

Advantages

Method overloading increases the readability of the program.

Method 1 — Different Number of Parameters

public int add(int a, int b) {
    int sum = a + b;
    return sum;
}

// adding three integer values
public int add(int a, int b, int c) {
    int sum = a + b + c;
    return sum;
}

Method 2 — Different Data Types

public int add(int a, int b, int c) {
    int sum = a + b + c;
    return sum;
}

// adding three double values
public double add(double a, double b, double c) {
    double sum = a + b + c;
    return sum;
}

Method 3 — Different Parameter Order

public void geekIdentity(String name, int id) {
    System.out.println(
        "geekName :" + name + " " + "Id :" + id);
}

public void geekIdentity(int id, String name) {
    System.out.println(
        "geekName :" + name + " " + "Id :" + id);
}

Operator Overloading in Java

The notes state that Java does not support general operator overloading, with + being an overloaded operator for addition and String concatenation.

class Test {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        System.out.println(a + b);          // 30 - addition
        System.out.println(a + "ratan");    // 10ratan - concatenation
    }
}
Types of overloading listed: Method overloading, constructor overloading, and operator overloading.

9. Inheritance

Inheritance is the process by which one object/class acquires the properties of another object/class. The notes use the example of getting properties from parents and their parents.

Java inheritance examples include using methods inherited from the Object class.

Inheritance Types Shown in the Notes

Single

A → B

Multilevel

A → B → C

Hierarchical

A → B, C, D

Hybrid

Combination of inheritance forms as illustrated in the notes.

Multiple

The diagram illustrates A + B → C; the text notes that Java does not support multiple inheritance of classes.

10. Method Overriding

Overriding allows a subclass to define behavior specific to the subclass type. A subclass can implement a parent class method according to its requirement.

Rules for Java Method Overriding

  • The argument list must be exactly the same as the overridden method.
  • The return type should be the same or a subtype of the superclass method's return type.
  • The access level cannot be more restrictive than the overridden method.
  • If the superclass method is public, the subclass method cannot be private or protected.
  • Instance methods can be overridden only if they are inherited by the subclass.
  • A final method cannot be overridden.
  • A static method cannot be overridden, although it can be re-declared.
  • If a method cannot be inherited, it cannot be overridden.
  • A subclass in the same package can override inherited superclass methods that are not private or final.
  • A subclass in a different package can override non-final methods declared public or protected, as described in the notes.
  • An overriding method can throw unchecked exceptions regardless of whether the overridden method throws exceptions.
  • An overriding method should not throw new or broader checked exceptions than the overridden method.
  • An overriding method can throw narrower or fewer exceptions.
  • Constructors cannot be overridden.

Simple Overriding Example

class Animal {
    void move() {
        System.out.println("Animal moves");
    }
}

class Dog extends Animal {
    @Override
    void move() {
        System.out.println("Dog moves");
    }
}

11. Covariant Return Types in Java

A covariant return type refers to the return type of an overriding method. It allows the overriding method to narrow the return type without requiring a cast, provided the return type is a subclass of the original method's return type.

The notes state that this applies to non-primitive return types and has been supported from Java 5 onwards.

class SuperClass {
    SuperClass get() {
        System.out.println("SuperClass");
        return this;
    }
}

public class Tester extends SuperClass {
    Tester get() {
        System.out.println("SubClass");
        return this;
    }

    public static void main(String[] args) {
        SuperClass tester = new Tester();
        tester.get();
    }
}

Output:

SubClass

12. Method Overloading vs Method Overriding

Method OverloadingMethod Overriding
Method name is same, parameters must be different.Method name and parameters must be same.
Can be achieved within a single Java class.Requires parent-child class relationship.
Compile-time polymorphism.Runtime polymorphism.
Static / early binding.Dynamic / late binding.
Can differ by number, type or order of parameters.Argument list must match the parent method.
Return type alone cannot distinguish overloaded methods.Covariant return types are allowed for non-primitive return types.

13. Method Hiding — Static Methods

The notes distinguish overriding from method hiding. A static method is bound to the class, whereas instance methods are associated with objects.

class Parent {
    static void m1() {
        System.out.println("parent m1()");
    }
}

class Child extends Parent {
    static void m1() {
        System.out.println("child m1()");
    }

    public static void main(String[] args) {
        Parent p = new Child();
        p.m1();
    }
}

Output shown in the notes:

parent m1()
Key distinction: The notes state that static methods cannot be overridden; when a subclass declares a static method with the same signature, this is method hiding rather than overriding.

Quick Revision

TopicKey Point
ClassLogical entity / blueprint containing data members and methods.
ObjectPhysical entity / instance of a class.
EncapsulationWrapping data and methods together and controlling access.
AbstractionHide implementation details and expose necessary information.
PolymorphismOne interface with multiple definitions/forms.
OverloadingSame method name with different parameter lists.
InheritanceAcquiring properties/behavior from another class.
OverridingSubclass provides a specific implementation of an inherited method.
Covariant ReturnOverriding method may return a subtype of the parent method's return type.
Method HidingStatic method with the same signature in subclass; not overriding.