1 Object Oriented Programming Fundamentals

Advanced Java Programming · Unit 1

Object-Oriented Programming Fundamentals

Exam-focused notes for Object-Oriented Programming Fundamentals (Advanced Java Programming, BIT401): what the TU syllabus asks and how it has actually been tested, with 7 solved past questions from this unit.

Object-Oriented Programming Fundamentals in short

Object-oriented programming (OOP) builds a program from classes and objects. This chapter covers the Java features that give OOP its power: overloading, overriding, inheritance, interfaces, inner classes, packages and the Object class.

Object-Oriented Programming Fundamentals: notes

Method overloading and overriding

Method overloading means writing many methods with the same name in one class. Their parameter lists must differ in number, type or order. The return type alone cannot separate them. Java picks the method at compile time, so this is compile-time polymorphism.

public class Calc {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
    int add(int a, int b, int c) { return a + b + c; }
    public static void main(String[] args) {
        Calc c = new Calc();
        System.out.println(c.add(2, 3));
        System.out.println(c.add(2.5, 1.5));
        System.out.println(c.add(1, 2, 3));
    }
}

Method overriding means a subclass gives its own body to a method it inherits. The name, parameters and return type must match. The access level cannot be reduced. Java picks the method at run time from the real object type, so this is run-time polymorphism.

class Person {
    int id; String name;
    void getPerson(int id, String name) { this.id = id; this.name = name; }
    void showPerson() { System.out.println(id + " " + name); }
}
class Student extends Person {
    @Override
    void showPerson() {
        super.showPerson();
        System.out.println("Role: student");
    }
}
public class OverrideDemo {
    public static void main(String[] args) {
        Person p = new Student();
        p.getPerson(1, "Sita");
        p.showPerson();
    }
}
OverloadingOverriding
Same classParent and child class
Parameters must differParameters must be the same
Resolved at compile timeResolved at run time
Static and private methods allowedStatic, private and final methods cannot be overridden

Inheritance and class hierarchies

Inheritance lets a class (the subclass) reuse the fields and methods of another class (the superclass). It uses the extends keyword. It supports code reuse and a clear "is-a" relation. Java allows single, multilevel and hierarchical inheritance among classes. A class cannot extend two classes, which avoids the diamond problem. Multiple inheritance of type is done through interfaces.

class Animal { void eat() { System.out.println("eats"); } }
class Dog extends Animal { void bark() { System.out.println("barks"); } }

The super keyword reaches the parent's members and constructors. Private members are not inherited directly.

What this unit covers

  • Method overloading and overriding
  • Inheritance and class hierarchies
  • Interface design and implementation
  • Abstract classes and polymorphism
  • Constructor chaining
  • Inner classes and anonymous inner classes
  • Package definition and organization
  • Final keyword and immutability
  • Object class and its methods

Inner classes and anonymous inner classes

2081 · 10 marks

How do you create inner class and anonymous inner class? Create a class EMPLOYEE with data members Emp_ID, Name and Occupation, and write those objects to the file DOC.DAT whose occupations is doctor.[10]

An inner class is a class defined within another class. It has access to the outer class's members. Syntax: Creating objects: An anonymous inner class is a class without a name, typically used to override methods of an interface or abstract class on-the-fly. Syntax: --- Output: --- - Serializable...

Open this answer on its own page →

Package definition and organization

2081 · 5 marks

Define package. What is the use of final keyword and finally block? [5]

A package is a namespace mechanism in Java used to organize and group related classes, interfaces, and sub-packages into a hierarchical structure. Packages help avoid naming conflicts and provide a way to control access to classes and members. Example structure: --- The final keyword in Java is u...

Open this answer on its own page →

Interface design and implementation

2080 · 10 marks

Why do we need interface? Define an interface named shape with area ( ) method. Create a class named Rectangle with length and breadth circle with radius that implements shape interface. Now create the object of both classes and display their area.[10]

Interfaces are needed for the following reasons: 1. Abstraction: Interfaces define a contract that specifies what methods a class must implement, without specifying how they should be implemented. 2. Polymorphism: Interfaces allow objects of different classes to be treated uniformly through a com...

Open this answer on its own page →

Constructor chaining

2080 · 5 marks

Describe the chain of constructor with example. [5]

Constructor chaining is a technique in object-oriented programming where one constructor calls another constructor of the same class or parent class. This allows code reuse and initialization of objects in a flexible manner. One constructor calls another constructor of the same class using the th...

Open this answer on its own page →

Final keyword and immutability

2080 · 5 marks

Write short notes on a. Final keyword b. Object class [5]

The final keyword in Java is a modifier used to restrict modification. It can be applied in three contexts: 1. Final Variables: - Once assigned, the value cannot be changed - Must be initialized when declared or in the constructor - Example: 2. Final Methods: - Cannot be overridden by subclasses ...

Open this answer on its own page →

Method overloading and overriding

0 · 10 marks

Discuss the concept of method overriding. Write a program to create Person class with variables id, and name. Include methods getPerson() and showPerson() in the class. Again, create another class named Employee, which is child of person class. Include member variable salary, and methods getEmployee(), and showEmployee() in the class. Again, create a third class named Typist, which is child of Employee. Include variable typespeed, and methods getTypist(), and showTypist() in the class. Finally, create two objects of Typist class and read and display their details.[10]

Show solved answer

Method Overriding and Multilevel Inheritance - Model Answer

Concept of Method Overriding

Method Overriding is a feature of Object-Oriented Programming that allows a child class to provide a specific implementation of a method that is already defined in its parent class. When a method in a child class has the same name, return type, and parameters as a method in the parent class, the child class method overrides (replaces) the parent class method.

Key Points:

  • Enables runtime polymorphism
  • Child class method must have the same signature as parent class method
  • Allows customized behavior in child classes while maintaining the parent interface
  • Improves code reusability and flexibility

Program Implementation

import java.util.Scanner;

// Parent Class: Person
class Person {
    protected int id;
    protected String name;
    
    public void getPerson() {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter ID: ");
        id = sc.nextInt();
        sc.nextLine();  // consume newline
        System.out.print("Enter Name: ");
        name = sc.nextLine();
    }
    
    public void showPerson() {
        System.out.println("ID: " + id);
        System.out.println("Name: " + name);
    }
}

// Child Class: Employee (inherits from Person)
class Employee extends Person {
    protected double salary;
    
    public void getEmployee() {
        getPerson();  // call parent method
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter Salary: ");
        salary = sc.nextDouble();
    }
    
    public void showEmployee() {
        showPerson();  // call parent method
        System.out.println("Salary: " + salary);
    }
}

// Child Class: Typist (inherits from Employee)
class Typist extends Employee {
    private int typespeed;
    
    public void getTypist() {
        getEmployee();  // call parent method
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter Typing Speed (words/min): ");
        typespeed = sc.nextInt();
    }
    
    public void showTypist() {
        showEmployee();  // call parent method
        System.out.println("Typing Speed: " + typespeed + " words/min");
    }
}

// Main Class
public class TypistDemo {
    public static void main(String[] args) {
        System.out.println("=== Typist Information System ===\n");
        
        // Create array of Typist objects
        Typist[] typists = new Typist[2];
        
        // Read details for two Typist objects
        for (int i = 0; i < 2; i++) {
            typists[i] = new Typist();
            System.out.println("\n--- Enter Details for Typist " + (i + 1) + " ---");
            typists[i].getTypist();
        }
        
        // Display details for two Typist objects
        System.out.println("\n\n=== Typist Details ===");
        for (int i = 0; i < 2; i++) {
            System.out.println("\n--- Typist " + (i + 1) + " ---");
            typists[i].showTypist();
        }
    }
}

Sample Output

=== Typist Information System ===

--- Enter Details for Typist 1 ---
Enter ID: 101
Enter Name: Ram Kumar
Enter Salary: 25000
Enter Typing Speed (words/min): 60

--- Enter Details for Typist 2 ---
Enter ID: 102
Enter Name: Sita Sharma
Enter Salary: 28000
Enter Typing Speed (words/min): 75


=== Typist Details ===

--- Typist 1 ---
ID: 101
Name: Ram Kumar
Salary: 25000.0
Typing Speed: 60 words/min

--- Typist 2 ---
ID: 102
Name: Sita Sharma
Salary: 28000.0
Typing Speed: 75 words/min

Explanation of Inheritance Hierarchy

Person (Base Class)
  ↓
Employee (Child of Person)
  ↓
Typist (Child of Employee - Multilevel Inheritance)
  • Person: Contains basic attributes (id, name) and methods
  • Employee: Extends Person, adds salary attribute and overrides display methods
  • Typist: Extends Employee, adds typespeed attribute and overrides display methods

Each child class calls parent methods using method names, demonstrating method overriding where showEmployee() overrides showPerson(), and showTypist() overrides showEmployee().

Open this answer on its own page →

0 · 5 marks

What is method overloading? Explain with example. [5]

Show solved answer

Method Overloading

Definition

Method overloading is a feature of Object-Oriented Programming that allows a class to have multiple methods with the same name but different parameters. It is a way to implement compile-time (static) polymorphism.

The methods must differ in:

  • Number of parameters, OR
  • Type of parameters, OR
  • Order of parameters

Rules for Method Overloading

  1. Methods must have the same name
  2. Methods must have different parameter lists
  3. Return type alone is NOT sufficient for overloading
  4. Access modifiers can be different

Example

class Calculator {
    
    // Method 1: Add two integers
    public int add(int a, int b) {
        return a + b;
    }
    
    // Method 2: Add three integers (different number of parameters)
    public int add(int a, int b, int c) {
        return a + b + c;
    }
    
    // Method 3: Add two doubles (different type of parameters)
    public double add(double a, double b) {
        return a + b;
    }
    
    // Method 4: Add int and double (different order/type)
    public double add(int a, double b) {
        return a + b;
    }
}

// Usage
public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        
        System.out.println(calc.add(5, 10));           // Calls Method 1: 15
        System.out.println(calc.add(5, 10, 15));       // Calls Method 2: 30
        System.out.println(calc.add(5.5, 10.5));       // Calls Method 3: 16.0
        System.out.println(calc.add(5, 10.5));         // Calls Method 4: 15.5
    }
}

Advantages

  • Improves code readability and usability
  • Makes the API intuitive (same operation, same method name)
  • Reduces confusion with multiple method names for similar operations
Open this answer on its own page →