📜  构造函数和方法之间的区别

📅  最后修改于: 2021-09-16 10:22:01             🧑  作者: Mango

Java是一种基于纯 OOPS 概念的编程语言。因此,在Java,所有变量、数据和语句都必须存在于类中。这些类由构造函数和方法组成。方法和构造函数在很多方面彼此不同。

构造函数
构造函数用于初始化对象的状态。与方法一样,构造函数也包含在创建对象时执行的语句(即指令)的集合。每次使用new()关键字创建对象时,都会调用至少一个构造函数(可以是默认构造函数)来为同一类的数据成员分配初始值。

示例

// Java Program to illustrate constructor
  
import java.io.*;
  
class Geek {
    int num;
    String name;
  
    // This would be invoked while an object
    // of that class created.
    Geek()
    {
        System.out.println("Constructor called");
    }
}
  
class GFG {
    public static void main(String[] args)
    {
        // this would invoke default constructor.
        Geek geek1 = new Geek();
  
        // Default constructor provides the default
        // values to the object like 0, null
        System.out.println(geek1.name);
        System.out.println(geek1.num);
    }
}
输出:
Constructor called
null
0

方法
方法是执行某些特定任务并将结果返回给调用者的语句的集合。一个方法可以执行一些特定的任务而不返回任何东西。方法允许我们重用代码而无需重新输入代码。在Java,每个方法都必须是某个类的一部分,这与 C、C++ 和Python等语言不同。

示例

// Java Program to illustrate methods
  
import java.io.*;
  
class Addition {
  
    int sum = 0;
  
    public int addTwoInt(int a, int b)
    {
  
        // Adding two integer value.
        sum = a + b;
  
        // Returning summation of two values.
        return sum;
    }
}
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating an instance of Addition class
        Addition add = new Addition();
  
        // Calling addTwoInt() method
        // to add two integer
        // using instance created
        // in above step.
        int s = add.addTwoInt(1, 2);
  
        System.out.println("Sum of two "
                           + "integer values: "
                           + s);
    }
}
输出:
Sum of two integer values: 3

构造函数方法之间的差异:

Constructors Methods
A Constructor is a block of code that initializes a newly created object. A Method is a collection of statements which returns a value upon its execution.
A Constructor can be used to initialize an object. A Method consists of Java code to be executed.
A Constructor is invoked implicitly by the system. A Method is invoked by the programmer.
A Constructor is invoked when a object is created using the keyword new. A Method is invoked through method calls.
A Constructor doesn’t have a return type. A Method must have a return type.
A Constructor initializes a object that doesn’t exist. A Method does operations on an already created object.
A Constructor’s name must be same as the name of the class. A Method’s name can be anything.
A class can have many Constructors but must not have the same parameters. A class can have many methods but must not have the same parameters.
A Constructor cannot be inherited by subclasses. A Method can be inherited by subclasses.