Summary:Java also uses constructors, and also provides a garbage collector (garbage collector), which will automatically release memory resources when they are no longer in use.
This article is shared from Huawei Cloud Community “One Article Takes You to Understand Constructors in Java”, author: One of the Universe.
C++ introduces the concept of a constructor (also known as a constructor), which is automatically called when an object is createdspecial method.
Java also uses constructors, and also provides a garbage collector (garbage collector), which will automatically release memory resources when they are no longer in use.
constructor definition
In Java, you can ensure the initialization of each object by writing a constructor. But there are two problems here:
- Any name used by this constructor may conflict with a member of the class;
- The compiler is responsible for calling the constructor, so it must always know which method to call.
The solution adopted by the C++ language is toThe constructor and the class name definition are the sameJava also adopted this scheme.
The role of the constructor is to create an instance of a new class. When an object is created, the JVM uses a constructor and allocates memory space for it.
Grammatical structures
class ClassName {
ClassName() {
}
}
For example, in the example below, we create a constructor named ReLearnConstructor. Inside the constructor, we are initializing the value of the hello variable. :
public class ReLearnConstructor {
String hello; // 属性
// 构造器
public ReLearnConstructor() {
hello = "Hello, Constructor!";
}
public static void main(String[] args) {
ReLearnConstructor rc = new ReLearnConstructor();
System.out.println(rc.hello);
}
}
Note the statement that creates an object of the ReLearnConstructor class: ReLearnConstructor rc = new ReLearnConstructor();
Here, when the object is created, the ReLearnConstructor constructor is called. And, the value of the hello variable is initialized.
So the value of the printed hello is:
constructor purpose
The purpose of the constructor is toInitialize the state of the object, to assign values to all declared properties. If we don’t have a custom constructor, the JVM will assign default values for these properties.
primitive typeDefault value for:
- Integer type is 0
- Float type is 0.0
- Boolean type is false
For other Java reference types, the default value is null, which means that the property of the reference type is not assigned any value.
These default values can be viewed later in code.
constructor class
In Java, there are three types of constructors:
- parameterless constructor
- parameterized constructor
- default constructor
parameterless constructor
Like methods, Java constructors may or may not have any parameters. If the constructor does not accept any parameters, it is called a parameterless constructor. For example, the ReLearnConstructor constructor in the above code is:
// 无参构造器
public ReLearnConstructor() {
hello = "Hello, Constructor!";
}
parameterized constructor
Literally, a constructor with parameters is called a parameterized constructor. So why do you need to use a parameterized constructor?
Parameterized constructors can be used forDifferent objects provide different initialized values. E.g:
public class ReLearnConstructor {
String languages;
// 接受单个参数的构造器
public ReLearnConstructor(String lang) {
languages = lang;
System.out.println("我在学习 " + languages + " 语言!");
}
public static void main(String[] args) {
// 向构造器中传入不同的值
ReLearnConstructor rc1 = new ReLearnConstructor("Java");
ReLearnConstructor rc2 = new ReLearnConstructor("Go");
ReLearnConstructor rc3 = new ReLearnConstructor("Python");
}
}
operation result:
default constructor
If we don’t create any constructor, Java compiler will automatically create a parameterless constructor during program execution.This constructor is calleddefault constructor. Let’s look at an example;
public class ReLearnConstructor {
String languages;
int a;
boolean b;
float c;
public static void main(String[] args) {
ReLearnConstructor rc = new ReLearnConstructor();
System.out.println("默认值:");
System.out.println("languages:" + rc.languages);
System.out.println("a:" + rc.a);
System.out.println("b:" + rc.b);
System.out.println("c:" + rc.c);
}
}
operation result:
默认值:
languages:null
a:0
b:false
c:0.0
As you can see, we haven’t created any constructors yet. Therefore, the Java compiler automatically creates a default constructor. The above table is verified.
The difference between native methods and constructors
- The constructor must have the same name as the class defined in Java
- Constructors do not return any type while methods do not return any value and methods have a return type or void
- When an object is created, the constructor is called only once, while the method can be called any number of times
If we don’t use constructors to assign values to properties, we can first use the new operator to obtain an instance of the class, and use the class’s setter method to set the value, as follows:
import java.util.Arrays;
class Person
{
private String name;
private int age;
@Override
public String toString() {
return Arrays.asList(name, String.valueOf(age)).toString();
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
// getters
}
// Initialize an object in Java
class Main
{
public static void main(String[] args)
{
Person person = new Person();
person.setName("Yuzhou1su");
person.setAge(22);
System.out.println(person);
}
}
Initializing through the constructor saves our setter method.
Here’s an example:
import java.util.Arrays;
class Person {
private String name;
private int age;
// 构造器
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return Arrays.asList(name, String.valueOf(age)).toString();
}
}
class SimpleConstructor {
public static void main(String[] args) {
Person person = new Person("Yuzhou1su", 22);
System.out.println(person);
}
}
operation result:
constructor overloading
Similar to Java method overloading, we can also create two or more constructors with different parameters. This is called constructor overloading.
public class ReLearnConstructor {
String language;
public ReLearnConstructor() {
this.language = "Java";
}
// 构造器
public ReLearnConstructor(String language) {
this.language = language;
}
public void getName() {
System.out.println("编程语言:" + this.language);
}
public static void main(String[] args) {
ReLearnConstructor rc1 = new ReLearnConstructor();
ReLearnConstructor rc2 = new ReLearnConstructor("Python");
rc1.getName();
rc2.getName();
}
}
In the above example, we have two constructors: ReLearnConstructor() and ReLearnConstructor(String language). Here, both constructors initialize the value of the variable language with different values. Depending on the parameters passed when creating the object, different constructors are called and different values are assigned.
operation result:
编程语言:Java
编程语言:Python
copy constructor
A copy construction method in Java is a construction method that uses an object of the class to construct another object.
A copy constructor is a special constructor used to create a new object as a copy of an existing object. It only takes one parameter, which will be another instance of the same class. We can explicitly call another constructor from within a copy constructor using the this() statement:
public class ReLearnConstructor {
private String language;
// 构造器
public ReLearnConstructor(String language) {
this.language = language;
}
// 拷贝构造器
public ReLearnConstructor(ReLearnConstructor rc) {
this.language = rc.language;
}
public void getName() {
System.out.println("编程语言:" + this.language);
}
public static void main(String[] args) {
ReLearnConstructor rc = new ReLearnConstructor("Python");
ReLearnConstructor copyOfrc = new ReLearnConstructor(rc);
rc.getName();
copyOfrc.getName();
}
}
operation result:
编程语言:Python
编程语言:Python
Useful when you need to copy a complex object with multiple member variables or want to construct a deep copy of an existing object.
anonymous inner class
In addition to the method of using the constructor described above, another way to initialize an object is to use “double brace initialization”.This will create aanonymous inner class, which has only one instance initializer. This method is not recommended.
import java.util.Arrays;
class Person
{
private String name;
private int age;
@Override
public String toString() {
return Arrays.asList(name, String.valueOf(age)).toString();
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
// getters
}
// Initialize an object in Java
class Main
{
public static void main(String[] args)
{
// Anonymous class
Person person = new Person() {{
// Initializer block
setName("Yuzhou1su");
setAge(22);
}};
System.out.println(person);
}
}
Summarize
- Constructors are called implicitly when an object is instantiated.
- The two rules for creating constructors are: The name of the constructor should be the same as the class. Java constructors cannot have return types.
- If a class has no constructor, the Java compiler automatically creates a default constructor at runtime. The default constructor initializes instance variables with default values. For example int variable will be initialized to 0
- Constructor type:
- no-argument constructor – a constructor that takes no parameters parameterized constructor
- Constructors that take parameters – Constructors that take parameters
- Default Constructor – The Java compiler will automatically create a constructor if not explicitly defined.
- Constructors cannot be modified by abstract, static or final
The compiler will report the following error:
Illegal modifier for the constructor in type ReLearnConstructor; only public, protected & private are permitted
- Constructors can be overloaded but not overridden
Click to follow and learn about Huawei Cloud’s fresh technologies for the first time~
#article #understand #constructor #JavaHuawei #Cloud #Developer #Alliances #personal #space #News Fast Delivery