Home>Article>Java> Difference between Java constructors and normal methods

Difference between Java constructors and normal methods

Guanhui
Guanhui Original
2020-05-30 11:29:14 13336browse

Difference between Java constructors and normal methods

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to check java version Next article:How to check java version