search
HomeJavajavaTutorialConstructor overloading using static blocks in Java

Constructor overloading using static blocks in Java

Sep 06, 2023 pm 02:41 PM
static blockconstructoroverload

Constructor overloading using static blocks in Java

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 of

Example

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 of

Example

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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool