Constructor in C #

Source: Internet
Author: User

The first time I heard the constructor term in C ++, I encountered it again in C.

When creating a class, because the object's status (data) is not very clear, you need to initialize it. For example, if we want to create an object in the rectangle class or create a rectangle, we must first determine its length and width. If we cannot determine its length and width, then we cannot create a rectangle. So we need to use a function in this rectangular class to construct all objects in this class-constructor. Since this function is used to create a new object, it cannot be stored after the object, so we must declare and define it in the class.

If there is a class named MyClass, its defined constructor framework is as follows:

public class MyClass{    public MyClass()    {    }}

Here is an example of how to calculate the area of a rectangle:

First, declare a rectangle class:

Class rectangle {public rectangle (int w, int h) // constructor declaration {width = w; high = h;} public int area () {return width * high ;} private int width; private int high ;}


Second, instantiate the class as A to complete initialization.

Program {static void Main (string [] args) {rectangle A = new rectangle (3, 4); // initialization Console is executed when object A is created. writeLine ("the rectangle area is {0}",. area ());}}

Finally, it should be noted that the constructor does not return values, and a class can have multiple constructor. When using a constructor with parameters, you need to write a constructor with null parameters.

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.