Skip to content
IT-306 · Java Programming Lab/Quick Revision Short Notes

Java Programming Lab (IT-306) - Unit 2 Short Notes

UNIT 2: Object-Oriented Programming (OOP) Fundamentals

2.1 Classes and Objects: The Building Blocks

  • Class: A blueprint/template that defines the structure (fields) and behavior (methods) of objects.

    • Syntax: class ClassName { // fields, methods }
  • Object: A concrete instance of a class created at runtime.

    • Instantiation: ClassName obj = new ClassName();

    • Reference Variable: obj holds the memory address of the object, not the object itself.

    • Member Access: Use dot operator . (e.g., obj.field, obj.method()).

  • Variables:

    • Instance Variables: Declared inside the class, outside methods. Each object has its own copy. Created with new.

    • Local Variables: Declared inside a method/block. Exist only during method execution.

  • Constructors:

    • Special method called when an object is created. Same name as class, no return type.

    • Default Constructor: Provided by compiler if no constructor is defined. Initializes fields to default values (e.g., 0, null).

    • Parameterized Constructor: Accepts arguments to initialize fields.

    • Constructor Overloading: Multiple constructors with different parameter lists.

    • this Keyword: Refers to the current object instance. Used to:

      1. Resolve variable shadowing (distinguish instance variable from parameter).

      2. Call another constructor in the same class (this(...)).

      3. Pass the current object as a parameter.

  • Method Overloading:

    • Multiple methods in the same class with the same name but different parameters (type, number, or order).

    • Achieves compile-time polymorphism (static binding). Method call is resolved at compile time based on the reference type.

    • Rules: Must differ in parameter list. Return type and access modifier can differ but are not sufficient for overloading.

[!TIP] Common Pitfall: Confusing overloading (same class, different params) with overriding (superclass-subclass, same signature).

2.2 Encapsulation and Data Hiding

  • Goal: Bundle data (fields) and methods (behaviors) together, and restrict direct access to internal state.

  • Access Modifiers: Control visibility of classes, fields, and methods.

    | Modifier | Class | Package | Subclass | World | |----------|-------|---------|----------|-------| | private | ✅ | ❌ | ❌ | ❌ | | default (package-private) | ✅ | ✅ | ❌ | ❌ | | protected | ✅ | ✅ | ✅ | ❌ | | public | ✅ | ✅ | ✅ | ✅ |

  • Implementation:

    1. Declare fields as private.

    2. Provide public getter (accessor) and setter (mutator) methods to controlled access.

    3. Add validation logic inside setters if needed.

  • Benefits: Prevents invalid state changes, increases flexibility (internal implementation can change without affecting clients), improves maintainability.

2.3 Inheritance: Achieving Reusability

  • Concept: A mechanism where a new class (subclass/child) acquires properties and behaviors of an existing class (superclass/parent). Promotes code reuse.

  • Syntax: class Subclass extends Superclass { ... }

  • Inheritance Chain: A subclass inherits all non-private members (fields and methods) of its direct superclass. Constructors are not inherited.

  • super Keyword: Reference to the immediate superclass.

    • super(): Calls the superclass constructor. Must be the first statement in a subclass constructor.

    • super.variable / super.method(): Accesses hidden superclass members (if subclass has a field/method with same name).

  • Types of Inheritance in Java:

    • Single: One subclass inherits from one superclass. (e.g., Car extends Vehicle)

    • Multilevel: A chain of inheritance. (e.g., Car extends Vehicle extends Object)

    • Hierarchical: Multiple subclasses inherit from one superclass.

    • Multiple: NOT SUPPORTED for classes (a class cannot extend more than one class). Achieved via interfaces.

    • Hybrid: Combination of above.

[!TIP] Constructor Execution Order: When creating a subclass object, superclass constructor executes first (top of hierarchy down to Object), then subclass constructor.

2.4 Polymorphism: Many Forms

  • Method Overriding:

    • Redefining a non-static, non-final, non-private method of the superclass in the subclass.

    • Rules:

      1. Same method signature (name + parameter types).

      2. Return type must be the same or a covariant subtype (Java 5+).

      3. Access modifier cannot be more restrictive.

      4. Cannot throw new or broader checked exceptions.

    • @Override Annotation: Best practice. Informs compiler to check for overriding rules. Prevents errors (e.g., due to typo in method name).

    • Runtime Polymorphism (Dynamic Method Dispatch): The JVM decides at runtime which overridden method to call based on the actual object type, not the reference type.

  • Applying Polymorphism:

    • A superclass reference variable can hold an object of any of its subclasses.

    • Example:

      
      Animal a = new Dog(); // Upcasting (implicit)
      
      a.makeSound(); // Calls Dog's makeSound() at runtime
      
      
    • Enables writing generic code that works with objects of multiple related types.

2.5 Static and Final Keywords

  • static Members:

    • static Variables (Class Variables): Belong to the class, not individual objects. Shared among all instances. Loaded when class is loaded.

    • static Methods (Class Methods): Can be called without an object (ClassName.method()). Cannot use this or super. Can only directly access static members.

    • Static Block: static { ... }. Executed once when the class is first loaded. Used for static initializations.

  • final Keyword: "Cannot be changed."

    • final Variable: A constant. Must be initialized exactly once (at declaration or in constructor). Primitive: value cannot change. Reference: reference cannot point to another object (but object state can change if mutable).

    • final Method: Cannot be overridden by subclasses.

    • final Class: Cannot be subclassed (inherited). (e.g., String, Integer).

2.6 Practical Implementation & Common Lab Patterns

  • Creating a Simple Hierarchy:

    • Example: Person (superclass) -> Student & Employee (subclasses).

    • Constructor Chaining: Subclass constructor should call super(...) to initialize inherited fields. If omitted, compiler inserts super().

  • instanceof Operator:

    • Purpose: Check if an object is an instance of a specific class or interface at runtime.

    • Syntax: obj instanceof ClassName → returns boolean.

    • Use Case: Safe downcasting.

      
      if (obj instanceof Student) {
      
          Student s = (Student) obj; // Safe downcast
      
      }
      
      
  • Type Casting:

    • Upcasting: Subclass object → Superclass reference. Implicit and safe.

      
      Animal a = new Dog(); // No cast needed
      
      
    • Downcasting: Superclass reference → Subclass reference. Explicit and risky. Throws ClassCastException if the actual object is not of the target subclass.

      
      Animal a = new Dog();
      
      Dog d = (Dog) a; // Explicit cast, safe here
      
      
  • Common Pitfalls & Debugging:

    • NullPointerException: Calling a method/accessing field on a null reference.

    • Shadowing vs Overriding:

      • Shadowing: Subclass declares a field with the same name as a superclass field. Accessed via super.field.

      • Overriding: Subclass provides a new implementation for a method. Invoked via dynamic dispatch.

    • Constructor Chain Failure: If superclass has no default constructor and subclass constructor doesn't explicitly call super(...), compilation error.

    • ClassCastException: Attempting invalid downcasting. Always use instanceof to check before downcasting.

[!TIP] Golden Rule for Casting: Upcast freely, downcast with instanceof check.

Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in