The difference between Java constructors and ordinary methods
1. The name of the constructor must be exactly the same as the class name in which it is defined. There is no return type, not even void.
2. There must be a constructor in the class. If not, the system will automatically add a no-argument constructor. Interfaces do not allow instantiation, so there are no constructors in interfaces.
3. It cannot be modified by static, final, synchronized, abstract and native.
4. The construction method is automatically executed when initializing the object. Generally, it cannot be called explicitly directly. When there are multiple construction methods in the same class, the Java compilation system will automatically follow the parameters in the last parentheses during initialization. Numbers and parameter types are automatically matched one-to-one. Complete the constructor call.
5. There are two types of construction methods: construction method without parameters and construction method with parameters.
Construction method without parameters
class person{ public person(){ System.out.println("无参的构造方法被调用了。。。"); } } class Ex11{ public static void main(String[] args){ person p=new person(); } }
Construction method with parameters (the purpose is to assign values to object instance variables)
class person{ int age; public person(int a){ age=a; } public void speak(){ System.out.println("I am "+age+" years old"); } } class Ex11{ public static void main(String[] args){ person p=new person(); p.speak(); } }
Recommended tutorials: "Java Tutorial" "PHP Tutorial"
The above is the detailed content of Difference between Java constructors and normal methods. For more information, please follow other related articles on the PHP Chinese website!