Constructor: java Constructor

Source: Internet
Author: User

Constructor: java Constructor

Constructor is a special method used to initialize an object. It is called when an object is created with new. If no constructor is defined in a class, the system automatically creates a constructor without parameters for the class, and the method body does not contain any statements, when the constructor of the defined class is displayed, the system will no longer automatically create the default constructor. Syntax:

[Modifier] Class Name ([parameter list]) {initialize object statement ;}

The constructor has the following features:

1. constructor is a special method. Every class in java has a constructor to initialize an object of this class.

2. the constructor has the same name as the class name and does not return any data type.

3. the constructor generally uses the public type to modify the constructor so that class instances can be created at any location.

4. Overloading is often used to construct methods.

5. the constructor can only be called by the new operator, but cannot be explicitly called using "object. constructor.

Instance:

public class Student{private String name;private int age;}

If no constructor is defined in this class, the system automatically adds the default constructor: public Student () {}. when an object is created with new, the constructor can only be constructed like this: student s = new Student (); // call the construction method without Parameters

Instance:

Public class Student {private String name; private int age; public Student (String name) {// constructor containing a parameter this. name = name;} public Student (String name, int age) {// constructor with two parameters this. name = name; this. age = age ;}}

This class defines two constructor methods. The system no longer provides default constructor methods.

You can also provide more constructor methods in the class definition. You can create one or more parameters based on the defined constructor when constructing an object.

 

  

Related Article

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.