Understanding of construction methods in Java

Source: Internet
Author: User

A method that is automatically executed during a class instantiation is called a construction method, and it does not require you to invoke it manually. The construction method can do some initialization work during the instantiation of the class. The name of the construction method must be the same as the name of the class, and there is no return value. Each class has a constructor method. If you do not explicitly define a construction method for a class, the Java compiler will provide a default constructor for the class

The following is an example of the use of a construction method:

1   Public classdog{22String name;33intAge ;44//constructor Function55 Dog (String name1,intage1) {66 name =name1;77 Age =Age1;88 System.out.println ("Thank the Master for adopting me");99         }Ten10 One11voidbark () { ASystem.out.println ("Bark, don't come over"); -13         } -14 the15voidhungry () { -System.out.println ("Master, I'm hungry.")); -17         } -18 +19 Public Static voidMain (String arg[]) { -Dog Mydog =NewDog ("Floral", 3);//Declaration + instantiation + initialization Mydog +21st//Accessing member variables AString name =Mydog.name; at23intAge =Mydog.age; -System.out.println ("I am a puppy, my name is" + name + ", I" + Age + "old")); -25//access Method -26Mydog.bark (); -27mydog.hungry (); -28         } in29}

The result of the operation is:

Thank you, Master, for adopting me.

I'm a puppy, my name is flower, I'm 3 years old.

Bark, don't come over.

Master, I'm hungry.

Understanding of construction methods 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.