Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A public constructor in Java is a distinct, method-like construct with a public access modifier, invoked automatically during object creation using the new keyword. The public modifier grants the widest possible visibility, allowing the class to be instantiated from any other class across different packages, provided that the package is accessible under the Java Platform Module System (JPMS) restrictions (i.e., the package is explicitly exported or opened in the module-info.java declaration).

Syntax

public class ClassName {
    
    // Public constructor declaration
    public ClassName(Type parameter) {
        // Initialization logic
    }
}

Technical Characteristics

  • Identifier Matching: The constructor’s identifier must exactly match the simple name of the class in which it resides.
  • Omission of Return Type: Constructors strictly lack a return type. Declaring a return type, even void, causes the Java compiler to treat the declaration as a standard method rather than a constructor.
  • Access Level: The public keyword allows the constructor to be invoked by the JVM, subclasses, and external classes, subject to module-level encapsulation boundaries.
  • Overloading: A class can declare multiple public constructors. The Java compiler differentiates them via their constructor signatures (the number, type, and order of parameters).
  • Constructor Chaining: A public constructor can invoke another constructor within the same class using the this() keyword, or a superclass constructor using the super() keyword. This invocation must be the first statement in the constructor body.

Compiler Behavior and Default Constructors

If a class contains no explicit constructor declarations, the Java compiler automatically injects a default no-argument constructor during compilation. The access modifier of this implicit constructor mirrors the access modifier of the class. Therefore, if a class is declared public and lacks explicit constructors, the compiler generates a public default constructor. Once any explicit constructor (public or otherwise) is defined, the compiler bypasses the automatic generation of the default constructor.

Code Visualization

public class NetworkClient {
    private String endpoint;
    private int port;

    // Public no-argument constructor
    public NetworkClient() {
        // Invokes the overloaded public constructor below
        this("localhost", 8080); 
    }

    // Overloaded public constructor with parameters
    public NetworkClient(String endpoint, int port) {
        this.endpoint = endpoint;
        this.port = port;
    }
}
Master Java with Deep Grasping Methodology!Learn More