CompSci Notes

Overview of Constructors in Java

  • Constructors are special methods used to initialize objects of a class.

  • The concept involves understanding the default constructor provided by Java.

Default Constructor

  • Definition: A constructor that Java automatically provides when no constructor is explicitly defined by the programmer.

  • Case of Provision: Only provided when no constructors have been written.

  • Characteristics:

    • Allows for zero arguments.

    • Initializes class fields to default values:

    • Numeric instance fields are set to 0.

    • char instance fields are set to an empty character ('\u0000').

    • Object instance fields (like String) are set to null.

    • Boolean fields are set to false.

Custom Constructors

  • Importance of explicit constructors in classes with parameters:

    • If a constructor with one or more parameters is defined, Java will not provide a default constructor.

    • If both constructors are required, both must be explicitly defined.

No-Argument Constructor

  • Purpose: Allows the creation of an object with no parameters.

  • If a programmer defines a constructor with parameters (e.g., multiple arguments), they should also implement a no-argument constructor to prevent issues with using default field values.

  • Initialization Rules: All constructors should correctly initialize all fields. If they don’t, Java will use the default values for uninitialized fields.

Example Class: Inventory Item

  • Definition of class and different types of constructors in InventoryItem:

    • Zero-Argument Constructor: Initializes fields using default values.

    • One-Argument Constructor: Accepts a description and initializes it while others take default values.

    • Two-Argument Constructor: Accepts values for both description and units, performs initialization accordingly.

Usage of Constructors

  • When creating an InventoryItem, the output depends on which constructor is called:

    • Default Constructor Call:item1 = new InventoryItem();

    • Fields print as follows:

      • Description: null

      • Units: 0

    • Example of Accessing Fields: Attempting to access attributes directly can lead to issues if fields are left as null.

Handling Null Values

  • Printing fields that haven’t been initialized may lead directly to runtime errors, such as:

    • NullPointerException: Occurs when trying to access a method or field of a null object.

    • Ideally, constructors should lead to initialization states that avoid such run-time issues, especially for fields that could be critical for operations.

Best Practices in Constructors

  • Consider providing non-null default values in the no-argument constructor:

    • Instead of using null for strings, prefer empty string as a default to prevent errors from accessing methods.

Argument Passing in Java

  • Pass by Value: Java methods receive arguments by value, meaning:

    • A copy of the variable’s value is passed, not the variable itself.

    • This is important for both primitive types and reference types.

Primitive and Object Types

  • When passing primitives, the value is copied directly:

    • A change in the copy does not affect the original variable.

  • When passing objects, a reference (address) of the object is copied:

    • Both the original reference and the copy point to the same object in memory.

    • If the object’s contents are modified through the copied reference, such changes reflect in the original reference.

Modifying Object Properties

  • If an object is passed to a method, the method can modify its properties using its public methods (like setters).

  • Example illustrates the reference being passed around with changing values modifying the original object’s state.

Returning Objects from Methods

  • You can return objects from methods:

    • The returning method must have a return type that matches the object being returned.

    • Example usage includes methods that create new objects and return references to them directly, avoiding the need for temporary variables.

Summary

  • Java remains a pass-by-value language even with objects, with the nuance that it copies references instead of full objects.

  • Modifications in passed reference objects are propagated across the calls, affecting all references pointing to that object.

  • Guard against unexpected modifications by implementing proper encapsulation (private fields) and using public methods for access.

  • Always ensure to provide constructors that align with the intended object state and avoid null references where possible to create robust and debuggable code.