[Javase Study Notes]-7.2 differences between constructors and general functions

Source: Internet
Author: User

[Javase Study Notes]-7.2 differences between constructors and general functions

In this section, we will briefly learn the differences between constructors and general functions.

So what are their differences? combined with the previous section, we can summarize the following two differences:

The first difference:

Constructor: when an object is created, the corresponding constructor is called to initialize the object.

General functions: After an object is created, the function is called only when the function is required.

This means that when creating an object, the constructor must be called, but the general function is not necessarily called.

The second difference:

Constructor: it is called only once when an object is created.

General functions: After an object is created, it can be called multiple times.

Let's take a look at the example:

Class Person {private String name; private int age; Person () {System. out. println ("person run");} public void speak () {System. out. println (name + ":" + age );}}

Class ConsDemo {public static void main (String [] args) {Person p = new Person (); // The constructor p is called at this time. speak (); // call the speak Method p twice. speak ();}}
We can see that when the object p is created, the constructor in the Person class is called only once. In general, the speak method is called only after an object is created and can be called any times.


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.