Constructors for Java

Source: Internet
Author: User

Initialization and cleanup are two issues that involve security. Both C + + and Java introduce the concept of a constructor (constructor), a special method that is called automatically when an object is created.

You can assume that each class you write defines a initialize () method. This method is used every time the object is used. In Java, by providing a constructor, the designer of the class ensures that each object is initialized.

In Java, the constructor is the same as the name of the class. If no constructor is defined, then Java automatically calls the default constructor.

Let's start by looking at a simple class with a constructor:

Class Yes () {Yes () {System.out.print ("yes")}}public class Breakyizhan {public static void main (string[] args) {for (int i=0; I <5;i++) {new Yes ()}}/* (www.breakyizhan.com) output is: Yes Yes Yes */

The above constructor is a constructor that does not accept any arguments, called the default constructor, and does not have a parametric constructor. But there is also a constructor with parameters, as follows:

Class Yes () {Yes (int i) {System.out.print ("yes" + i)}}public class Breakyizhan {public static void main (  String[] args) {for (int i=0; I <6;i++) {new Yes (i)}}/* (www.breakyizhan.com) output is: Yes 0 Yes 1 Yes 2 Yes 3 Yes 4 Yes 5 */

A constructor is a special type of method that does not return the same value. This is the special method that Java uses to initialize, and in a class, there can be many constructors to initialize the class when it is created.

For more Java content, please visit:

Break Easy Station

Constructors for Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.