[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.