The act of instantiating an object calls its corresponding constructor, which is the basis for many features in object-oriented programming. It's worth noting that in any program that uses objects, there will invariably be a default constructor - the compiler automatically creates it for seamless use.
In this discussion, we will delve into constructor overloading of static blocks in Java. Constructor overloading is the concept of defining multiple constructors with different parameters in a class.
grammar
Public class class_name { Class_name() { } Class_name(par1, par2..) { } }
Using constructors with static blocks provides more power and flexibility during object initialization.
algorithm
To use a static block to overload the constructor, please follow the steps below -
Step 1 - Create a class with multiple constructors with different parameters.
-
Step 2 - Create a static block using the "static" keyword
This block is executed once when the class is loaded into memory.
Step 3- When loading a class, first the static block is executed and then the constructor is executed when the object is created.
Step 4 - The constructor will be called based on the arguments provided.
Method 1: Define a separate static block
This approach involves defining static blocks and overloaded constructors separately.
The Chinese translation ofExample
is:Example
Class Class_name{ Static { } Public class_name(){ } Public class_name(int value) { } Public class_name(string name) { } //Other methods }
In this approach, a class can have overloaded constructors with different parameter lists, which also include initialization code. There is also a separate static block for static initialization of the class. This block will be executed once.
Example
In this example, we will show method 1
class Emp { int id, exp;String name;static String company; static { company = "XYZ Corp"; } public Emp(){ System.out.println("-" + "\t" + "-" + "\t" + "-" + "\t" + "\t" + "-"); } public Emp(int id, String name){ System.out.println(id + "\t" + name + "\t" + company + "\t" + exp); } public Emp(int id, String name, int exp) { System.out.println(id + "\t" + name + "\t" + company + "\t" + exp); } } public class Way2Class { public static void main(String[] args) { System.out.println("Id" + "\t" + "Name" + "\t" + "Company" + "\t" + "Exp"); Emp obj1 = new Emp(001, "Apoorva"); Emp obj2 = new Emp(004, "Anu", 10); Emp obj3 = new Emp(); } }
Output
Id Name Company Exp 1 Apoorva XYZ Corp 0 4 Anu XYZ Corp 10 - - - -
illustrate
In a company, employees with any number of years of experience will work for the same company. So if no value is passed in company variable then it automatically sets the same company name as company. For this we use static blocks.
Method 2: Call static method from constructor
To perform shared initialization code, you can declare static methods in the class and call them from the constructor.
The Chinese translation ofExample
is:Example
public class Way2Class { private int value; private String name; private static void initialize() { System.out.println("Common initialization code"); } public Way2Class() { initialize(); value = 0; name = "Default"; System.out.println("No-arg constructor called"); } public Way2Class(int value) { initialize(); this.value = value; name = "Value"; System.out.println("Int constructor called"); } public Way2Class(String name) { initialize(); value = 0; this.name = name; System.out.println("String constructor called"); } public static void main(String[] args) { Way2Class obj1 = new Way2Class(); Way2Class obj2 = new Way2Class(10); Way2Class obj3 = new Way2Class("Hello"); } }
Output
Common initialization code No-arg constructor called Common initialization code Int constructor called Common initialization code String constructor called
illustrate
The Way2Class class in this picture contains three constructors, each of which calls the static initialize () method to execute shared initialization code. Each constructor calls the static function initialize() specified within the class. Based on the given parameters, the appropriate constructor is called during object creation, and the static method initialize() is used to execute the public initialization code.
Comparison between Method 1 and Method 2
standard |
method 1 |
Method 2 |
---|---|---|
type |
Separate static block |
Call static method from constructor |
method |
Reuse common static methods with different constructors. |
Independent static methods and common constructors. |
Method logic |
Constructor overloading and static blocks |
Constructor overloading and static blocks |
in conclusion
While approach 2 (static method called from constructor) provides greater flexibility in code organization and inheritance, approach 1 (multiple constructors with common code) is more independent and simpler. The choice between the two methods depends on the specific requirements and design considerations of the current project.
The above is the detailed content of Constructor overloading using static blocks in Java. For more information, please follow other related articles on the PHP Chinese website!

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
