Home Java Javagetting Started what is java constructor

what is java constructor

Nov 12, 2019 am 09:26 AM
java Constructor

what is java constructor

The constructor is a member of the object-oriented system. The constructor can be called a constructor. Its function name is the same as the class name. There is no need to define a return value type and no specific return value. . The constructor is a function called when constructing a created object. Its function is to initialize the object. All objects created must be initialized through the constructor. If there is no constructor defined in a class, the class will have a default constructor with empty parameters. If a specified constructor is defined in a class, there is no default constructor in the class.

When we are born, some people are given names after they are born, but some people are already given names as soon as they are born. So how do we assign a value to an object once it is created in Java?

what is java constructor

what is java constructor

1. The role of the constructor:

The role of the constructor: perform operations on the object initialization.

As shown in the figure:

what is java constructor

2. The difference between constructors and ordinary functions:

(1) General Functions are used to define the functionality that an object should have. The constructor defines some content that the object should have when it is created before calling the function. That is, the initialization content of the object.

(2) The constructor is called by jvm when the object is created to initialize the object. Generally, a function will be executed when the object calls the function after the object is created.

(3) Ordinary functions can be called multiple times using objects, and the constructor is called when the object is created.

(4) The function name of the constructor must be the same as the class name, and ordinary functions only need to comply with the naming rules of identifiers.

(5) The constructor has no return value type.

3. Details to pay attention to in the constructor:

(1) When there is no constructor defined in the class, the system will assign an empty parameter to the class. 's constructor. This is the default constructor in the class. When a constructor is customized in a class, the default constructor is gone.

Note: It can be verified through javap command.

(2) Multiple constructors can be defined in a class to perform different initialization. Multiple constructors exist in a class and are embodied in the form of overloading. Because the names of the constructors are all the same.

class Perosn{
private int id;
private String name;
private int age;
public Perosn(){
cry();
}
public Perosn(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void cry(){
System.out.println("哇哇哇....");
}
}
Copy after login

Question: Every child is required to cry when he is born. This code has two constructors. If every child is required to cry when he is born, cry() needs to be called in different constructors. ) function, but this will cause code duplication problem, so how to solve it? Construct code blocks.

4. Construction code block:

The function of the construction code block: to uniformly initialize all objects.

class Perosn{
private int id;
private String name;
private int age;
{
cry();// 每个Person对象创建出来都会执行这里的代码
}
public Perosn(){
cry();
}
public Perosn(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void cry(){
System.out.println("哇哇哇....");
}
}
Copy after login

Specific functions:

1: Initialize the object. Runs as soon as the object is created and takes precedence over the constructor.

2: Difference from constructor

(1) The difference between constructed code block and constructor function. Constructed code block is to uniformly initialize all objects, and constructor function is to The corresponding object is initialized.

(2) The function of the construction code block: Its function is to extract the common information in all construction methods.

For example, a child cries uniformly upon birth

The code is as follows:

class Boy {
 
String name;
int age;
String gender;
     // 构造代码块,给所有对象进行初始化。
{
System.out.println("哭。。。");
}
     
Boy() {
System.out.println("无参构造");
}
 
Boy(String n, int a, String g) {
name = n;
age = a;
gender = g;
System.out.println("有参构造");
}
 
void run() {
System.out.println("跑...");
}
 
}
 
class Demo9 {
 
public static void main(String[] args) {
 
System.out.println();
Boy b = new Boy();
 
Boy b2 = new Boy("jack", 1, "男");
 
}
}
Copy after login

php Chinese website, a large number of free Java introductory tutorials, welcome online study!

The above is the detailed content of what is java constructor. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles