How to construct in Java

Source: Internet
Author: User

First, define a class, named car, to achieve the following two construction methods:

1  Public classCar {2     3     //here is a constructor method that cannot have a return value type,4      PublicCar () {5         6System.out.println ("Car constructor-no arguments");7         8     }9     Ten     //Here is also a construction method, with the method of constructing a parameter One      PublicCar (String p_message) { ASYSTEM.OUT.PRINTLN ("car's constructor-parameter is:" +p_message); -     } -  the}

The above code should pay attention to:

1. The name and class name of the constructor method must be the same.

2. The constructor method is not a return value type, and cannot be used with the static modifier.

The following is the code for the subclass:

1  Public classAudiextendscar{2     3      PublicAudi () {4         //TODO auto-generated Constructor stub5SYSTEM.OUT.PRINTLN ("The construction method of Audi-no reference");6     }7     8      PublicAudi (intP_wheel) {9         Ten     } One  A}

The above code needs to be noted:

1. Subclasses inherit only the default constructor method of the parent class.

Then write a test master method, as follows:

1  Public classMaintest {2 3     /**4      * @paramargs5      */6      Public Static voidMain (string[] args) {7         //TODO auto-generated Method Stub8         9Audi A3 =NewAudi ();Ten audi a4 = new Audi (4); One  A     } -  -}

The result after running the code is:

The constructor of car-the construction method of no parameter Audi -no parameter

Car's constructor-no parameters

Audi's construction method-with parameters: 4

So here's a conclusion:

The main function of the construction method is to complete the initialization of the object, which can pass the parameters that define the object to the domain of the object.

When you create an object, you first call the parent class default constructor to initialize the object, and then call the child class's own defined constructor.

How to construct in 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.