search
HomeJavajavaTutorialJava basic tutorial constructor and method overloading

In methods and data members, we mentioned that objects in Java are initialized when they are created. During initialization, the object's data members are assigned initial values. We can initialize it explicitly. If we do not assign an initial value to the data member, the data member will take a default initial value based on its type.

Explicit initialization requires us to determine the initial value when writing the program, which is sometimes very inconvenient. We can use constructor to initialize objects. Constructors can initialize data members and specify specific operations. These operations are performed automatically when the object is created.

Define the constructor

The constructor is a method. Like normal methods, we define constructors in the class. The constructor has the following basic characteristics:

1. The name of the constructor is the same as the name of the class
2. The constructor has no return value

We define the constructor of the Human class:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

public class Test

{

public static void main(String[] args)

{

Human aPerson = new Human(160);

System.out .println(aPerson.getHeight());

}

}

class Human

{

/**

   * constructor

   */

Human(int h)

{

This.height = h;

System.out.println("I'm born");

}

/**

   * accessor

   */

int getHeight ()

{

return this.height;

}

int height;

}

The above program will print

I'm born
160

The constructor can receive a parameter list like a normal method. Here, the constructor Human() receives an integer as parameter. In the body of the method, we assign the integer parameter to the data member height. The constructor does two things when the object is created:

The constructor can receive a parameter list like a normal method. Here, the constructor Human() receives an integer as parameter. In the body of the method, we assign the integer parameter to the data member height. The constructor does two things when the object is created:

1. Provides an initial value for the data member this.height = h;
2. Performs specific initial operations System.out.println("I 'm born");

In this way, we can flexibly set the initial value when calling the constructor without being as constrained as display initialization.

How is the constructor called? When we create classes, we all use new Human(). In fact, we are calling the constructor of the Human class. When we do not define this method, Java will provide a blank constructor to be called when using new. But when we define a constructor, Java will call the defined constructor when creating an object. When calling, we provide a parameter of 160. You can also see from the final running results that the height of the object is indeed initialized to 160.

Priority of initialization method

In methods and data members, we can see that if we provide an explicit initial value, then the data member will adopt an explicit initial value instead of Default initial value. But if we both provide an explicit initial value and initialize the same data member in the constructor, the final initial value will be determined by the constructor. For example, in the following example:

public class Test
{
  public static void main(String[] args)
  {
    Human aPerson = new Human(160);
    System.out.println(aPerson.getHeight());
  }
 
}
 
class Human
{
  /**
   * constructor
   */
  Human(int h)
  {
    this.height = h; 
  }
 
  /**
   * accessor
   */
  int getHeight()
  {
    return this.height;
  }
 
  int height=170; // explicit initialization
}

The running result is:

160

The final initialization value of the object is consistent with the value in the construction method. Therefore:


##Build method> Explicit initial value> Default initial value

(In fact, the so-called priority is related to the execution order during initialization Related, I will go into this in depth later)

Method overloading

More than one constructor can be defined in a class, such as:

public class Test
{
  public static void main(String[] args)
  {
    Human neZha  = new Human(150, "shit");
    System.out.println(neZha.getHeight()); 
  }
 
}
 
class Human
{
  /**
   * constructor 1
   */
  Human(int h)
  {
    this.height = h;
    System.out.println("I'm born");
  }
 
  /**
   * constructor 2
   */
  Human(int h, String s)
  {
    this.height = h;
    System.out.println("Ne Zha: I'm born, " + s);
  }
 
  /**
   * accessor
   */
  int getHeight()
  {
    return this.height;
  }
 
  int height;
}

Running results:

Ne Zha: I'm born, shit
150

There are two constructors defined above, both named Human. The two constructors have different parameter lists.

When using new to create an object, Java will decide which constructor to build based on the provided parameters. For example, when building neZha, we provide two parameters: the integer 150 and the string "shit", which corresponds to the parameter list of the second build method, so Java will call the second build method.

In Java, Java will determine the method to be called based on both the method name and the parameter list. This is called method overloading. The build method can be overloaded, and ordinary methods can also be overloaded. For example, the breath() method below:

public class Test
{
  public static void main(String[] args)
  {
    Human aPerson = new Human();
    aPerson.breath(10);
  }
 
}
 
class Human
{
  /**
    * breath() 1
    */
  void breath()
  {
    System.out.println("hu...hu...");
  }
 
 
  /**
  * breath() 2
  */
  void breath(int rep)
  {
    int i;
    for(i = 0; i < rep; i++) {
      System.out.println("lu...lu...");
    }
  }
 
  int height;
}

Running results:

lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...

You can see that because it is provided when calling One parameter: the integer 10, so the second breath() method whose parameter list matches it is called.

Summarize

Constructor features: The same name as the class, no return value
Constructor purpose: Initialization, initial operation
Method overloading: method name + parameter list-> Which method is actually called

More For articles related to multiple Java basic tutorials on constructors and method overloading, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.