Home > Java > JavaBase > How to write constructor in java

How to write constructor in java

angryTom
Release: 2019-11-15 10:09:19
Original
7733 people have browsed it

How to write constructor in java

How to write a constructor in java

1. java constructor

Also called constructor, it is a special function in java. The function name is the same as the class name and has no return value.

Function: Generally used to initialize member properties and member methods, that is, after the new object is generated, the properties and methods of the object are called. (Recommended tutorial: java tutorial )

2. Characteristics of constructors

1. The function name is the same as the class name

2. There is no need to define the return value type. (Unlike the void type return value, void has no specific return value type; the constructor does not even have a type)

3. You cannot write a return statement. (There is no return value type, so there is no need for a return statement)

Note: General functions cannot call constructors, only constructors can call constructors.

3. Write a constructor

public class ConfunDemo {
    public static void main(String[] args) {
        // //输出Hello World。new对象一建立,就会调用对应的构造函数Confun(),并执行其中的println语句。
        Confun c1=new Confun();
    }
}
class Confun{        
    Confun(){
        //定义构造函数,输出Hello World
        System.out.println("Hellow World");
    }
}
Copy after login

Through the above example, we can easily write a constructor of our own, go and try it!

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

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template