简体   繁体   English

Java中的方法与构造方法

[英]Methods vs Constructors in Java

I have just started programming with Java. 我刚刚开始使用Java进行编程。 The text we use is lacking when talking about methods and constructors. 在谈论方法和构造函数时,我们缺少使用的文字。 I'm not sure what a method or a constructor is exactly and what makes each unique. 我不确定到底是什么方法或构造函数以及什么使每个方法唯一。 Can someone please help me define them and differentiate between the two? 有人可以帮我定义它们并区分两者吗?

The important difference between constructors and methods is that constructors initialize objects that are being created with the new operator, while methods perform operations on objects that already exist. 构造函数与方法之间的重要区别在于,构造函数初始化使用new运算符创建的对象,而方法对已存在的对象执行操作。

Constructors can't be called directly; 构造函数不能直接调用; they are called implicitly when the new keyword creates an object. new关键字创建对象时,将隐式调用它们。 Methods can be called directly on an object that has already been created with new . 可以直接在已使用new创建的对象上调用方法。

The definitions of constructors and methods look similar in code. 构造函数和方法的定义在代码中看起来相似。 They can take parameters, they can have modifiers (eg public ), and they have method bodies in braces. 它们可以采用参数,可以具有修饰符(例如public ),并且在括号中具有方法主体。

Constructors must be named with the same name as the class name. 构造函数的名称必须与类名称相同。 They can't return anything, even void (the object itself is the implicit return). 他们不能返回任何东西,甚至void (对象本身是隐含的回报)。

Methods must be declared to return something, although it can be void . 尽管必须为void ,但必须声明方法以返回某些内容。

The main difference is 主要区别是

1. Constructor are used to initialize the state of object,where as method is expose the behaviour of object. 1. 构造函数用于初始化对象的状态,其中方法公开对象的行为。

2. Constructor must not have return type where as method must have return type. 2. 构造函数不得具有返回类型,而as 方法必须具有返回类型。

3. Constructor name same as the class name where as method may or may not the same class name. 3. 构造函数名称与类名称相同,其中as 方法可能相同,也可能不同。

4. Constructor invoke implicitly where as method invoke explicitly. 4. 构造函数隐式调用,而方法显式调用。

5. Constructor compiler provide default constructor where as method compiler does't provide. 5. 构造函数编译器提供默认的构造函数,而方法编译器则不提供。

Other instructors and teaching assistants occasionally tell me that constructors are specialized methods. 其他讲师和助教有时会告诉我构造函数是专门的方法。 I always argue that in Java constructors are NOT specialized methods . 我一直认为Java构造函数不是专门的方法

If constructors were methods at all, I would expect them to have the same abilities as methods. 如果构造函数完全是方法,我希望它们具有与方法相同的功能。 That they would at least be similar in more ways than they are different. 至少它们之间的相似之处要多于不同之处。

How are constructors different than methods? 构造函数与方法有何不同? Let me count the ways... 让我来计算一下...

  1. Constructors must be invoked with the new operator while methods may not be invoked with the new operator. 构造函数必须使用new运算符调用,而方法不能使用new运算符调用。 Related: Constructors may not be called by name while methods must be called by name. 相关:构造函数不能按名称调用,而方法必须按名称调用。

  2. Constructors may not have a return type while methods must have a return type. 构造函数可能没有返回类型,而方法必须具有返回类型。

  3. If a method has the same name as the class, it must have a return type. 如果方法与类具有相同的名称,则它必须具有返回类型。 Otherwise, it is a constructor. 否则,它是一个构造函数。 The fact that you can have two MyClass() signatures in the same class definition which are treated differently should convince all that constructors and methods are different entities: 在同一个类定义中可以有两个MyClass()签名,这些签名被不同地对待,这一事实应使所有确信构造函数和方法是不同的实体:

     public class MyClass { public MyClass() { } // constructor public String MyClass() { return "MyClass() method"; } // method } 
  4. Constructors may initialize instance constants while methods may not. 构造函数可以初始化实例常量,而方法则不能。

  5. Public and protected constructors are not inherited while public and protected methods are inherited. 公共和受保护的构造函数不被继承,而公共和受保护的方法则被继承。

  6. Constructors may call the constructors of the super class or same class while methods may not call either super() or this(). 构造函数可以调用父类或同一个类的构造函数,而方法不能调用super()或this()。

So, what is similar about methods and constructors? 那么,方法和构造函数有何相似之处?

  1. They both have parameter lists. 它们都有参数列表。

  2. They both have blocks of code that will be executed when that block is either called directly (methods) or invoked via new (constructors). 它们都具有代码块,当该代码块被直接调用(方法)或通过new调用(构造函数)时将执行该代码块。

As for constructors and methods having the same visibility modifiers... fields and methods have more visibility modifiers in common. 至于具有相同可见性修饰符的构造函数和方法...字段和方法具有更多共同的可见性修饰符。

  1. Constructors may be: private , protected , public . 构造函数可以是: 私有的受保护的公共的

  2. Methods may be: private , protected , public , abstract , static , final , synchronized , native , strictfp . 方法可以是: 私有受保护公共抽象静态最终同步本机strictfp

  3. Data fields may be: private , protected , public , static , final , transient , volatile . 数据字段可以是: 私有受保护公共静态最终瞬态易失

In Conclusion 结论

In Java, the form and function of constructors is significantly different than for methods. 在Java中,构造函数的形式和功能与方法明显不同。 Thus, calling them specialized methods actually makes it harder for new programmers to learn the differences. 因此,将它们称为专用方法实际上会使新程序员更难学习差异。 They are much more different than similar and learning them as different entities is critical in Java. 它们比相似的东西有更多不同,学习不同的实体对于Java至关重要。

I do recognize that Java is different than other languages in this regard, namely C++, where the concept of specialized methods originates and is supported by the language rules. 我确实认识到Java在这方面与其他语言(即C ++)不同,在C ++中,专用方法的概念起源于语言规则并受其支持。 But, in Java, constructors are not methods at all, much less specialized methods. 但是,在Java中,构造函数根本不是方法,更不用说专门的方法了。

Even javadoc recognizes the differences between constructors and methods outweigh the similarities; 甚至javadoc都认识到构造函数和方法之间的差异远大于相似之处。 and provides a separate section for constructors. 并为构造函数提供了单独的部分。

In Java, classes you write are Objects. 在Java中,您编写的类是对象。 Constructors construct those objects. 构造函数构造这些对象。 For example if I have an Apple.class like so: 例如,如果我有一个像这样的Apple.class

public class Apple {
    //instance variables
    String type; // macintosh, green, red, ...

    /**
     * This is the default constructor that gets called when you use
     * Apple a = new Apple(); which creates an Apple object named a.
     */

    public Apple() {
        // in here you initialize instance variables, and sometimes but rarely
        // do other functionality (at least with basic objects)
        this.type = "macintosh"; // the 'this' keyword refers to 'this' object. so this.type refers to Apple's 'type' instance variable.
    }

    /**
     * this is another constructor with a parameter. You can have more than one
     * constructor as long as they have different parameters. It creates an Apple
     * object when called using Apple a = new Apple("someAppleType");
     */
    public Apple(String t) {
        // when the constructor is called (i.e new Apple() ) this code is executed
        this.type = t;
    }

    /**
     * methods in a class are functions. They are whatever functionality needed
     * for the object
     */
    public String someAppleRelatedMethod(){
        return "hello, Apple class!";
    }

    public static void main(String[] args) {
        // construct an apple
        Apple a = new Apple("green");
        // 'a' is now an Apple object and has all the methods and
        // variables of the Apple class.
        // To use a method from 'a':
        String temp = a.someAppleRelatedMethod();
        System.out.println(temp);
        System.out.println("a's type is " + a.type);
    }
}

Hopefully I explained everything in the comments of the code, but here is a summary: Constructors 'construct' an object of type of the class. 希望我在代码的注释中解释了所有内容,但这是一个摘要:构造函数“构造”一个​​类类型的对象。 The constructor must be named the same thing as the class. 构造函数的名称必须与类相同。 They are mostly used for initializing instance varibales Methods are functionality of the objects. 它们主要用于初始化实例变量。方法是对象的功能。

A constructor is a special kind of method that allows you to create a new instance of a class. 构造函数是一种特殊的方法,它允许您创建类的新实例。 It concerns itself with initialization logic. 它涉及初始化逻辑。

A "method" is a "subroutine" is a "procedure" is a "function" is a "subprogram" is a ... The same concept goes under many different names, but basically is a named segment of code that you can "call" from some other code. “方法”是“子例程”是“过程”是“函数”是“子程序”是...同样的概念使用了许多不同的名称,但基本上是可以命名的代码段,调用”。 Generally the code is neatly packaged somehow, with a "header" of some sort which gives its name and parameters and a "body" set off by BEGIN & END or { & } or some such. 通常,代码以某种方式整齐地打包,带有某种“标头”,给出其名称和参数,以及一个“正文”,以BEGINEND{}等开头。

A "consrtructor" is a special form of method whose purpose is to initialize an instance of a class or structure. “构造器”是一种特殊形式的方法,其目的是初始化类或结构的实例。

In Java a method's header is <qualifiers> <return type> <method name> ( <parameter type 1> <parameter name 1>, <parameter type 2> <parameter name 2>, ...) <exceptions> and a method body is bracketed by {} . 在Java中,方法的标头是<qualifiers> <return type> <method name> ( <parameter type 1> <parameter name 1>, <parameter type 2> <parameter name 2>, ...) <exceptions>和一个方法主体用{}括起来。

And you can tell a constructor from other methods because the constructor has the class name for its <method name> and has no declared <return type> . 而且您可以从其他方法中得知构造函数,因为该构造函数具有其<method name>的类名称,并且没有声明的<return type>

(In Java, of course, you create a new class instance with the new operator -- new <class name> ( <parameter list> ) .) (当然,在Java中,您可以使用new运算符new <class name> ( <parameter list> )创建一个新的类实例。)

the difference r : r

  1. Constructor must have the name same as class but method can be made by any name. 构造函数的名称必须与类相同,但方法可以由任何名称组成。
  2. Constructor are not inherited automatically by child classes while child inherit method from their parent class unless they r protected by private keyword. 子类不会自动继承构造方法,而子类会从其父类继承方法,除非它们受private关键字保护。
  3. Constructor r called explicitly while methods implicitaly. 构造函数r隐式调用while方法。
  4. Constructor doesnot have any return type while method have. 方法具有时,构造函数没有任何返回类型。

Constructor is special function used to initialise the data member, where the methods are functions to perform specific task. 构造函数是用于初始化数据成员的特殊函数,其中方法是执行特定任务的函数。

Constructor name is the same name as the class name, where the method name may or may not or be class name. 构造函数名称与类名称相同,方法名称可以相同也可以不相同,也可以为类名称。

Constructor does not allow any return type, where methods allow return type. 构造函数不允许任何返回类型,其中方法允许返回类型。


Constructor typically is Method . 构造函数通常是Method

When we create object of a class new operator use then we invoked a special kind of method called constructor. 当我们创建使用new运算符的类的对象时,我们将调用一种称为构造函数的特殊方法。

Constructor used to perform initialization of instance variable. 构造函数,用于执行实例变量的初始化。

Code: 码:

public class Diff{

public Diff() { //same as class name so constructor 

        String A = "Local variable A in Constructor:";
        System.out.println(A+ "Contructor Print me");
    }
   public void Print(){
        String B = "Local variable B in Method";
        System.out.println(B+ "Method print me");
    } 


    public static void main(String args[]){
        Diff ob = new Diff();

        }
}

` `

  • Output: 输出:

    Local variable A in Constructor:Contructor Print me 构造函数:构造函数中的局部变量A

So,only show here Constructor method Diff() statement because we create Diff class object. 因此,仅在此处显示构造方法Diff()语句,因为我们创建了Diff类对象。 In that case constructor always come first to instantiate Class here class Diff(). 在这种情况下,构造函数总是最先在此处实例化Class Diff()的Class。

typically, 通常,

Constructor is set up feature. 构造函数设置功能。

Everything start with here, when we call ob object in the main method constructor takes this class and create copy and it's load into the " Java Virtual Machine Class loader " . 一切都从这里开始,当我们在main方法构造函数中调用ob对象时,将使用该类并创建副本,并将其加载到“ Java虚拟机类加载器”中。

This class loader takes this copy and load into memory,so we can now use it by referencing. 这个类加载器将这个副本加载到内存中,因此我们现在可以通过引用来使用它。

Constructor done its work then Method are come and done its real implementation. 构造函数完成其工作,然后Method并完成其实际实现。

In this program when we call 在这个程序中,当我们调用

ob.print();

then method will coming. 然后方法就会来。

Thanks 谢谢

Arindam 阿林丹

The Major difference is Given Below - 主要区别如下:

1: Constructor must have same name as the class name while this is not the case of methods 1:构造函数必须与类名具有相同的名称,而方法不是这种情况

class Calendar{
    int year = 0;
    int month= 0;

    //constructor
    public Calendar(int year, int month){
        this.year = year;
        this.month = month;
        System.out.println("Demo Constructor");
    }

    //Method
    public void Display(){

        System.out.println("Demo method");
    }
} 

2: Constructor initializes objects of a class whereas method does not. 2:构造函数初始化一个类的对象,而方法则不初始化。 Methods performs operations on objects that already exist. 方法对已经存在的对象执行操作。 In other words, to call a method we need an object of the class. 换句话说,要调用一个方法,我们需要一个类的对象。

public class Program {

    public static void main(String[] args) {

        //constructor will be called on object creation
        Calendar ins =  new Calendar(25, 5);

        //Methods will be called on object created
        ins.Display();

    }

}

3: Constructor does not have return type but a method must have a return type 3:构造函数没有返回类型,但是方法必须具有返回类型

class Calendar{

    //constructor – no return type
    public Calendar(int year, int month){

    }

    //Method have void return type
    public void Display(){

        System.out.println("Demo method");
    }
} 

Here are some main key differences between constructor and method in java 这是Java中的构造函数和方法之间的一些主要关键区别

  1. Constructors are called at the time of object creation automatically. 在创建对象时会自动调用构造函数。 But methods are not called during the time of object creation automatically. 但是在对象创建时不会自动调用方法。
  2. Constructor name must be same as the class name. 构造函数名称必须与类名称相同。 Method has no such protocol. 方法没有这样的协议。
  3. The constructors can't have any return type. 构造函数不能有任何返回类型。 Not even void. 甚至没有空。 But methods can have a return type and also void. 但是方法可以具有返回类型,并且也可以无效。 Click to know details - Difference between constructor and method in Java 单击以了解详细信息-Java中的构造函数和方法之间的区别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM