[Java] Constructors in Java

This article is for learning reference only!

In any object-oriented language, programmers define classes and create objects. In these scenarios, class members need an initializer. A constructor is a special method associated with a class that initializes the members of the class with the values ​​you want.

Although constructors are called implicitly by the runtime when an object is created, they can also be called explicitly. In this programming tutorial, we'll look at constructors, their benefits, and how developers can use constructors in Java.

What is a constructor in Java?

A constructor is a method or member function of a class that has the same name as the class it belongs to and whose sole purpose is to initialize class members. Therefore, you can use constructors to set initial values ​​for members of a class.

When you instantiate a class, a Java constructor is called implicitly. While there can be multiple constructors in a class, there can be one and only one destructor. Any class in Java must have at least one constructor.

It is important to note that a class implicitly provides a constructor even if the programmer has not written any constructor in the class. By default, this constructor provided by the runtime is called the default constructor. When a class is created using the new operator without any parameters , the default constructor of the class is called.

The following code example shows how to define a class in Java:

class MyFirstJavaClass {
    
    
  MyFirstJavaClass() {
    
    
    // This is the constructor body
  }
}

Note that in the preceding Java code examples, the name of the class and the name of the class's constructor are the same.

What is constructor overloading in Java?

Constructor overloading in Java is a way to create multiple constructors for the same class. This allows developers to create multiple constructors in a class with the same name but different signatures.

Note that overloaded constructors must have different signatures. The signature of a method in Java includes the method name , parameters , and return type .

Since the constructor does not have any return type, the parameter types and order of the overloaded constructor must be different. In other words, the signature of a constructor includes the type , number , and order of its parameters .

When a class has more than one constructor, the compiler uses overload resolution rules to determine which constructor will be called when an instance of the class is created. Overload resolution rules are used to ensure that the appropriate constructor is called based on the arguments passed in.

Note that class constructors can be overloaded but not overridden , because base and derived class constructors can never have the same name.

Constructors in Java can never be "virtual"

Constructors can neither be virtual nor return any value. To declare a method as virtual, you need to include the keyword virtual in its signature .

Subclass methods can override virtual methods. However, you can never override a base class constructor in a derived class. You cannot have virtual constructors (i.e. class constructors can never be virtual), but you can have virtual destructors.

The reason for this is that the virtual table or vtable will not be available in memory while the constructor is executing . A class's vtable is only available after the class's constructor has finished executing.

No-argument constructor and parameterized constructor in Java

Constructors can be either parameterless or parameterized . As the name implies, a no-argument constructor is a constructor that takes no parameters. The default constructor is the only no-argument constructor in the class. In other words, there can be one (and only one) parameterless constructor in a class.

A parameterized constructor is a constructor that can accept one or more parameters. While a class in Java can have one and only one parameterless constructor, you can have multiple parameterized constructors.

Now, please refer to the code sample given below. It shows how to implement no-argument constructors for classes in Java:

public class MyClass {
    
    
private int x;
public MyClass() {
    
    
x = 0;
System.out.println("No-argument constructor called...");
}
public static void main(String[] args) {
    
    
MyClass obj = new MyClass();
}
}

The following code example illustrates how to define a parametric constructor for a class in Java:

public class MyClass {
    
    
private int x;
private int y;
public MyClass(int i, int j) {
    
    
x = i;
y = j;
}
public int getValueOfX()
{
    
    
    return x;
}
public int getValueOfY()
{
    
    
    return y;
}
public static void main(String[] args) {
    
    
MyClass obj = new MyClass(5, 10);
System.out.printf("Printing the value of x : %d\n", obj.getValueOfX());
System.out.printf("Printing the value of y : %d", obj.getValueOfY());
}
}

Copy Constructor in Java

In Java, a copy constructor can be defined as a constructor that creates a new instance of a class by copying the current instance of the class. Use the copy constructor when you need to create a new instance of a class and then be able to change the state of the object without affecting the original object. Therefore, the state of the original object remains unchanged after being copied.

Following is the syntax to use copy constructor in Java −

MyClass(MyClass obj) {
    
    //这是复制构造函数的主体。 } 

To create a copy constructor for a class, the programmer should define a parametric constructor for the class where the parameters are of the same type as the class type. The following code example shows how to define a copy constructor in Java:

public class Product 
{
    
     
private int id; 
private String name; 
public Product(Product product) 
{
    
     
this.id = product.id; 
this.name = product.name; 
} 

There are two types of copy constructors that developers can use in Java: one that uses shallow copy and one that uses deep copy .

Execution order of constructors in Java inheritance

Constructors belonging to a class are called in the order in which the classes are inherited. Instead, calls to destructors follow the reverse order.

The following code example shows how to call a constructor in Java inheritance:

public class HelloWorld {
    
    
    public static void main(String []args) {
    
    
        C obj = new C();
    }
}
class A {
    
    
    public A() {
    
    
        System.out.println("Constructor of class A called...");
    }
}
class B extends A {
    
    
    public B() {
    
    
        System.out.println("\nConstructor of class B called...");
    }
}
class C extends B {
    
    
    public C() {
    
    
        System.out.println("Constructor of class C called...");
    }
}

When you execute the code above, the output in the console window looks like this:

Java Constructors Tutorial

Figure 1: Demonstrates that constructors are executed in inheritance order.

END

Although developers can initialize class members in other custom methods, it is better to define constructors to initialize them. Programmers should also explicitly define default constructors and write their own code to initialize class members - this also improves readability. It should be noted that in Java, the constructor cannot be abstract , final , static or native .

Guess you like

Origin blog.csdn.net/m0_47015897/article/details/131412360