Skip to content
Unit 2 Syllabus Note· Object Oriented Programming using JAVA

Object Oriented Programming using JAVA

Comprehensive exam revision notes for BCA-201N Unit 2 (Classes, Objects, Methods, Constructors & Inheritance). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.

Object Oriented Programming using JAVA

Classes, Objects, Methods, Constructors & Inheritance

Core Definitions & Key Concepts

What is the difference between a Class and an Object in Java

  • Class: A blueprint, template, or prototype defining the state (fields) and behavior (methods) common to all objects of that kind. It consumes no physical memory for instance fields.
  • Object: An active runtime instance of a class created via the new operator, occupying dedicated space in heap memory.

What is the role of the new operator and constructor in object instantiation

The new operator dynamically allocates memory on the heap for the new object and returns a memory reference. Immediately following allocation, the corresponding constructor executes to initialize the object's instance variables.

What is Constructor Overloading

Defining multiple constructors within the same class having the exact same name but differing parameter lists (different number, types, or order of arguments), allowing objects to be initialized in different ways.

What is the this keyword in Java

this is a reference variable referring to the current calling object. It is used to:

  1. Resolve name shadowing between instance variables and local parameters (this.x = x).
  2. Invoke another constructor in the same class (this(args) constructor chaining).
  3. Pass the current object as an argument.

What are the 4 Access Specifiers in Java

  1. private: Accessible only within the declaring class.
  2. default (package-private): Accessible by any class within the same package.
  3. protected: Accessible within the same package, and by subclasses in other packages.
  4. public: Accessible from any class in any package across the application.

What is the super keyword in Java

super is a reference variable used by a subclass to refer to its immediate superclass. It is used to:

  1. Invoke the superclass constructor (super(args) - must be the first statement).
  2. Access superclass instance variables hidden by subclass variables (super.speed).
  3. Call overridden superclass methods (super.display()).

Why does Java NOT support Multiple Inheritance of classes

To avoid the Diamond Problem ambiguity: if class C extends both A and B, and both A and B override the same method display(), the compiler cannot determine which version C inherits. Java resolves this by supporting multiple inheritance through interfaces only.

What is Dynamic Method Dispatch (Runtime Polymorphism)

The mechanism by which a call to an overridden method is resolved at runtime rather than compile time. When an overridden method is invoked via a superclass reference variable (Parent p = new Child()), Java determines which implementation to execute based on the actual type of the object being referred to.

What is the purpose of the final keyword in Java

  • final variable: Constant value that cannot be reassigned.
  • final method: Method that cannot be overridden by any subclass.
  • final class: Class that cannot be extended (subclassed), such as java.lang.String.

What is the static keyword in Java

static designates members (variables, methods, blocks, nested classes) that belong to the class itself rather than individual instances. Static variables share a single memory copy across all instances; static methods can be called directly without instantiating objects.

Conceptual & Architectural Analysis

Method Overloading and Method Overriding with Syntax Examples

FeatureMethod OverloadingMethod Overriding
ContextWithin the same classBetween Superclass and Subclass
Method SignatureMust differ in parameters (type, count)Must be identical (name, parameters, return type)
ResolutionCompile-time (Static binding)Run-time (Dynamic method dispatch)
Private / StaticCan overload private/static methodsCannot override private or static methods
Return TypeCan have different return typesMust be identical or covariant return type
AnnotationNone required@Override recommended

The Various Types of Inheritance Supported in Java with Diagrams

Java supports 3 forms of class inheritance directly:

  1. Single Inheritance: Class B extends Class A.
  2. Multilevel Inheritance: Class C extends Class B, and Class B extends Class A.
  3. Hierarchical Inheritance: Multiple subclasses (B, C, D) extend a single parent class A.

Note on Multiple & Hybrid Inheritance: Class-level multiple inheritance is prohibited to avoid method collision; it is implemented seamlessly using interface declarations.

Constructor Chaining using this() and super()

Constructor chaining is the process of calling one constructor from another constructor with respect to current object or superclass:

  • this() invokes an overloaded constructor in the same class.
  • super() invokes the constructor of the parent class.
  • Crucial Rule: Either this() or super() must be the very first statement inside a constructor body. If omitted, the Java compiler automatically inserts a default super() call as the first line.

What is an Abstract Class and how does it differ from a Concrete Class

An Abstract Class (declared with abstract) cannot be instantiated directly with new. It serves as a base class containing a mix of concrete (implemented) methods and abstract methods (method signatures without a body ending in semicolon). Subclasses must provide concrete implementations for all inherited abstract methods, unless the subclass is also declared abstract.

The Object Class (java.lang.Object) and its Core Methods

In Java, java.lang.Object is the root ancestor of all classes. Every class implicitly inherits from Object. Core methods include:

  • public String toString(): Returns text representation (ClassName@HexHashCode).
  • public boolean equals(Object obj): Compares object references (can be overridden for content equality).
  • public int hashCode(): Returns integer hash value for hashing collections.
  • protected Object clone(): Creates a field-by-field copy (requires Cloneable).
  • public final Class<?> getClass(): Returns runtime Class metadata object.
  • wait(), notify(), notifyAll(): Thread synchronization primitives.

In-Depth Analysis & Implementation

Develop an Enterprise Employee Payroll Management System in Java Demonstrating Classes, Inheritance, Constructor Chaining, Method Overriding, and Dynamic Polymorphism

Here is a complete model implementation:

System Architecture / Concept DiagramHorizontal Scroll Enabled
/**
 * University Examination Model Solution: BCA-201N Unit 2
 * Comprehensive Payroll System Demonstrating Multilevel Inheritance & Polymorphism
 */
abstract class Employee {
    protected int empId;
    protected String name;
    protected double basicSalary;

    // Parameterized constructor
    public Employee(int empId, String name, double basicSalary) {
        this.empId = empId;
        this.name = name;
        this.basicSalary = basicSalary;
    }

    // Abstract method to be overridden by subclasses
    public abstract double calculateNetSalary();

    public void displayProfile() {
        System.out.printf("ID: %d | Name: %-15s | Basic: Rs. %,10.2f", empId, name, basicSalary);
    }
}

// Full-Time Salaried Employee
class PermanentEmployee extends Employee {
    protected double hraPercentage;
    protected double daPercentage;

    public PermanentEmployee(int empId, String name, double basicSalary, double hra, double da) {
        super(empId, name, basicSalary); // Constructor chaining to superclass
        this.hraPercentage = hra;
        this.daPercentage = da;
    }

    @Override
    public double calculateNetSalary() {
        double hra = basicSalary * (hraPercentage / 100.0);
        double da = basicSalary * (daPercentage / 100.0);
        double pfDeduction = basicSalary * 0.12;
        return (basicSalary + hra + da) - pfDeduction;
    }

    @Override
    public void displayProfile() {
        super.displayProfile();
        System.out.printf(" | Net: Rs. %,10.2f [Permanent]%n", calculateNetSalary());
    }
}

// Executive Manager with performance incentives
class Manager extends PermanentEmployee {
    private double managementBonus;

    public Manager(int empId, String name, double basicSalary, double hra, double da, double bonus) {
        super(empId, name, basicSalary, hra, da); // Chaining to PermanentEmployee
        this.managementBonus = bonus;
    }

    @Override
    public double calculateNetSalary() {
        return super.calculateNetSalary() + managementBonus;
    }

    @Override
    public void displayProfile() {
        super.displayProfile();
        System.out.printf("   -> Includes Executive Bonus of Rs. %,.2f%n", managementBonus);
    }
}

public class PayrollApplication {
    public static void main(String[] args) {
        System.out.println("===============================================================");
        System.out.println("        XROUNDER ACADEMIC PAYROLL SYSTEM - BCA-201N            ");
        System.out.println("===============================================================");

        // Dynamic Polymorphism: Base class references pointing to subclass instances
        Employee[] staff = new Employee[] {
            new PermanentEmployee(101, "Aarav Sharma", 45000.0, 20.0, 15.0),
            new PermanentEmployee(102, "Neha Verma", 52000.0, 20.0, 15.0),
            new Manager(103, "Vikram Malhotra", 85000.0, 25.0, 20.0, 20000.0)
        };

        double totalPayroll = 0;
        for (Employee emp : staff) {
            emp.displayProfile(); // Dynamically dispatched at runtime
            totalPayroll += emp.calculateNetSalary();
        }

        System.out.println("---------------------------------------------------------------");
        System.out.printf("Total Monthly Enterprise Payroll Outflow: Rs. %,.2f%n", totalPayroll);
        System.out.println("===============================================================");
    }
}

Dynamic Method Dispatch in Depth with Virtual Method Tables (vtable) and Bytecode Mechanics

1. Architectural Concept

Dynamic Method Dispatch is the runtime mechanism underlying Java's runtime polymorphism. When a method is called on a reference variable Parent ref = new Child(), the compiler generates an invokevirtual bytecode instruction. The decision of which code address to jump to is deferred until execution.

2. Virtual Method Tables (vtable)

During class loading, the JVM builds an internal array of method function pointers for each loaded class called a vtable:

  • When a class overrides a parent method, the subclass vtable slot points to the subclass's compiled native code address.
  • When a class does not override a parent method, its vtable slot points directly to the parent's compiled method code.

3. Execution Step

  1. When ref.method() executes, the JVM reads the object's header to identify its exact concrete Class metadata.
  2. It indexes into that concrete class's vtable at the fixed method offset determined during linking.
  3. It fetches the function pointer and immediately jumps to the target code with negligible overhead (an indexed array lookup).

Write a Comprehensive Analysis of Access Modifiers, Package Visibility, and Information Hiding in Java

Information hiding restricts direct external access to internal data structures, preventing invalid state mutations. Java provides a 4-tier visibility model:

System Architecture / Concept DiagramHorizontal Scroll Enabled
+----------------------+---------+---------+-----------+-------+
| Access Specifier     | Class   | Package | Subclass  | World |
+----------------------+---------+---------+-----------+-------+
| private              |   YES   |   NO    |    NO     |  NO   |
| default (package)    |   YES   |   YES   |    NO     |  NO   |
| protected            |   YES   |   YES   |    YES    |  NO   |
| public               |   YES   |   YES   |    YES    |  YES  |
+----------------------+---------+---------+-----------+-------+

Best Practices for University & Enterprise Design:

  1. Always declare instance fields as private.
  2. Expose controlled access via accessor (getter) and mutator (setter) methods with strict input validation.
  3. Use protected selectively for hook methods designed to be overridden by subclasses.

Important Exam Points & Quick Revision

Master the payroll code structure. University examiners frequently ask for code demonstrating abstract classes, dynamic method dispatch, and constructor chaining with super() and this().

Your reading progress
0%

100% left on this page — finishing it closes the gap for Classes, Objects, Methods, Constructors & Inheritance.

Weak topic hint

Classes, Objects, Methods, Constructors & Inheritance still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.