java 构造函数和方法的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26824253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:41:04  来源:igfitidea点击:

Difference between constructors and methods

javamethodsconstructor

提问by Steven Zhao

Bellow is an example I found on Tutorials Points, an example of a constructor. I got most of them, but I just don't get why you need a constructor anda method.

Bellow 是我在 Tutorials Points 上找到的一个例子,一个构造函数的例子。我得到了大部分,但我不明白为什么你需要一个构造函数一个方法。

public Puppy(String name){
    System.out.println("Passed Name is :" + name ); 
}

My question is, what stops you from doing this instead?

我的问题是,是什么阻止你这样做呢?

public static void Puppy(String name){
    System.out.println("Passed Name is: "+name);
}

Doesn't these two do the same thing once called?

这两个不是一次调用就做同样的事情吗?

Here is the full program for reference:

这是完整的程序供参考:

public class Puppy {
    int puppyAge;

    public Puppy(String name) {
        System.out.println("Passed Name is :" + name); 
    }

    public void setAge(int age) {
        puppyAge = age;
    }

    public int getAge() {
        System.out.println("Puppy's age is :" + puppyAge); 
        //what does this return do? since the puppyAge is already printed above.
        return puppyAge;
    }

    public static void main(String []args){
        Puppy myPuppy = new Puppy("tommy");

        myPuppy.setAge(2);
        myPuppy.getAge();

        System.out.println("Variable Value :" + myPuppy.puppyAge); 
    }
}

回答by Dici

You did not get the basic concept of an instance, which is fundamental in OOP. If you want a metaphor, let's talk about cars.

您没有了解实例的基本概念,这是 OOP 的基础。如果你想要一个比喻,让我们谈谈汽车。

I'm pretty sure you know what a car is; you know that it enables you to move from one place to another, that it has 4 wheels and so on. It is a concept, and the actual car you have in your garage is an instanceof this concept (<=> class).

我很确定你知道什么是汽车;你知道它可以让你从一个地方移动到另一个地方,它有 4 个轮子等等。这是一个概念,你车库里的实际汽车就是这个概念的一个实例<=> class)。

A constructor's goal is to create an instance, not to print some text. Without a constructor, you will never be able to call a non-static method of your class. You won't be able to drive the concept of a car, you will need to build a car first.

构造函数的目标是创建一个实例,而不是打印一些文本。如果没有构造函数,您将永远无法调用类的非静态方法。你将无法驾驶汽车的概念,你需要先制造一辆汽车。

Just review those notions; you will get nowhere without it.

只需回顾一下这些概念;没有它,你将一事无成。

回答by felipeek

I guess your question is why the constructor is created using...

我想你的问题是为什么构造函数是使用...

public Puppy(String name)

...instead of...

...代替...

public static void Puppy(String name)

..., right?

..., 对?

If it is, firstly you should now that a constructor is a special methodowned by a class that is called whenever you create a new instance of that class. So if, for example, you have this class...

如果是,首先您应该知道构造函数是一个类拥有的特殊方法,每当您创建该类的新实例时都会调用该方法。所以,例如,如果你有这个类......

public class Clazz {
    public Clazz (String s) {
         System.out.println(s);
    }
}

..., then whenever you create a new instance of this class like...

...,然后每当您创建此类的新实例时,例如...

Clazz c = new Clazz("Hello World");

..., the constructor will be called and that method will be executed. (In this example, it would print "Hello World" on the screen.)

...,将调用构造函数并执行该方法。(在这个例子中,它会在屏幕上打印“Hello World”。)

That said, you can see that the constructor is a method, but it's a special method called when the class is instantiated. So, regarding your question, the reason why the constructor is right this way instead of a regular method header is to indicate to the compiler that it is a constructorand nota regular method. If you write public void Clazz ()instead of public Clazz (), then the compiler will not recognize your constructor, and will think it's just a regular method.

也就是说,您可以看到构造函数是一个方法,但它是在实例化类时调用的特殊方法。因此,关于您的问题,构造函数以这种方式而不是常规方法标头正确的原因是向编译器表明它是构造函数不是常规方法。如果您编写public void Clazz ()而不是public Clazz (),那么编译器将无法识别您的构造函数,并且会认为它只是一个常规方法。

Note that constructors never return anything, so it would not be necessary to use the voidkeyword. Also, there's no sense in making a constructor static, since the constructor is called when a new object is instantiated.

请注意,构造函数从不返回任何内容,因此没有必要使用void关键字。此外,将构造函数设为静态是没有意义的,因为在实例化新对象时会调用构造函数。

回答by turingcomplete

Constructors ARE methods, they are special types of methods, however. Constructors are methods that don't have a return type and must be named after their enclosing class. So why do we need constructors? well, that's how we can create instances of classes. When you want to create an instance of a certain class, you do so by calling its constructor. The constructor reserves memory for the object and returns a reference to the newly created object.

构造函数是方法,但是它们是特殊类型的方法。构造函数是没有返回类型并且必须以其封闭类命名的方法。那么为什么我们需要构造函数呢?好吧,这就是我们如何创建类的实例。当你想创建某个类的实例时,你可以通过调用它的构造函数来实现。构造函数为对象保留内存并返回对新创建对象的引用。

回答by Mr. Polywhirl

Stated in the Java Spec for Constructors:

Java Spec for Constructors 中说明

  • Constructors do not return anything, thus they have no return type.

    In all other respects, the constructor declaration looks just like a method declaration that has no result (§8.4.5).

  • You cannot override a constructor.

    Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.

  • They cannot access instance variables directly, instead they must use thisand superto delegate to the classes' variables.

    An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.

  • 构造函数不返回任何内容,因此它们没有返回类型。

    在所有其他方面,构造函数声明看起来就像一个没有结果的方法声明(第8.4.5 节)。

  • 您不能覆盖构造函数。

    构造函数声明不是成员。它们永远不会被继承,因此不会被隐藏或覆盖。

  • 它们不能直接访问实例变量,而是必须使用thissuper委托给类的变量。

    构造函数体中的显式构造函数调用语句不得引用在该类或任何超类中声明的任何实例变量或实例方法或内部类,或在任何表达式中使用 this 或 super;否则,会发生编译时错误。

回答by Hessam

There is a very big difference between constructors and methods. When you instantiate an object like it's done in the program

构造函数和方法之间有非常大的区别。当你像在程序中那样实例化一个对象时

Puppy myPuppy = new Puppy( "tommy" );

with the use of newkeyword the JVM calls the constructor to make the object. So constructors make objects that doesn't exist but methods are associated with objects that exist. You can read more at this link http://www.javaworld.com/article/2076204/core-java/understanding-constructors.html

JVM使用new关键字调用构造函数来创建对象。所以构造函数创建不存在的对象,但方法与存在的对象相关联。您可以在此链接中阅读更多内容 http://www.javaworld.com/article/2076204/core-java/understanding-constructors.html

回答by BrianT.

several good answers about constructors already.

已经有几个关于构造函数的好答案。

A minor point; you cannot have a static method with the same name as your class. That name is reservedfor constructors.

一个小问题;你不能有一个与你的类同名的静态方法。该名称是为构造函数保留的。

回答by Auberon

When you create a new instance of an object (Puppy doggy = new Puppy("Bobby");) the Constructor is immediately called. It constructs the new objects. It constructs it with the name "Bobby". (The Puppy is born with the name "Bobby"). Let's say our puppy is unsatisfied with its name and you want to change it to "Snoopy". Then you would call the method: doggy.setName("Snoopy");

当您创建对象 ( Puppy doggy = new Puppy("Bobby");) 的新实例时,会立即调用构造函数。它构造新对象。它使用名称“Bobby”构建它。(小狗出生时的名字是“鲍比”)。假设我们的小狗对它的名字不满意,你想把它改成“史努比”。然后,你会调用方法:doggy.setName("Snoopy");

回答by Qyriad

A constructor is a typeof method. Specifically it is called when you instantiate an object of that class. So in your example if you write:

构造函数是一个类型的方法的。具体来说,当您实例化该类的对象时会调用它。所以在你的例子中,如果你写:

Puppy pup = new Puppy("Rover");

You make an object called pupand instantiating that object, which allows you to use it. By instantiating it, you call the constructor specified, in this case: public Puppy(String name)which sets prints to "Rover", however this isn't really a good use of a constructor. What would make more sense would be to have String puppyName;as a field variable, and have this.puppyName = nameto set p.puppyNameequal to what is passed in the constructor.

您创建一个对象pup并实例化该对象,这样您就可以使用它。通过实例化它,您可以调用指定的构造函数,在这种情况下:public Puppy(String name)它将打印设置为"Rover",但这并不是构造函数的真正用途。更有意义的是将其String puppyName;作为字段变量,并且必须this.puppyName = name设置为p.puppyName等于构造函数中传递的内容。

回答by Spaceman Spiff

A constructor is supposed to be for setting up the object where as a method simply does some action with the object. Java is object oriented so the whole language revolves around the object. Constructors also can not return anything and must be used with new to return an instance of the object created where as methods can return anything or nothing at all.

构造函数应该用于设置对象,而方法只是对对象执行某些操作。Java 是面向对象的,因此整个语言都围绕着对象展开。构造函数也不能返回任何内容,并且必须与 new 一起使用以返回创建的对象的实例,其中方法可以返回任何内容或根本不返回任何内容。

回答by Ryan Sayles

A Constructordoes just that, it "constructs" the object that you are creating it technically is a specific type of Method. A Methodis used to modify the object, mostly to do a single piece of logic. See: single responsibility principle.

AConstructor就是这样做的,它“构造”您在技术上创建它的对象是特定类型的Method. AMethod是用来修改对象的,主要是做单条逻辑。见:single responsibility principle

Classes/methods should be simple and handle exact pieces of information for example take a Shapeobject, if you wanted it's attributes to be length, width, height, volume, area, ect... your constructor would have to be:

类/方法应该很简单并处理精确的信息,例如拿一个Shape对象,如果你希望它的属性是长度、宽度、高度、体积、面积等......你的构造函数必须是:

public Shape (double length, double width, double height, double volume, double area, ect...) {
    //code here
} 

(notice the name of this method should be the same as the name of the class, signifying a 'Constructor`)

(注意这个方法的名字应该和类的名字一样,表示一个'Constructor`)

this is what is know as a code smell, specifically: too many parameters. It is difficult to read, not very organized and just a bad way to write code. So instead, methods are used to set these variables:

这就是所谓的 a code smell,特别是:参数太多。它很难阅读,没有条理,而且是一种糟糕的代码编写方式。因此,使用方法来设置这些变量:

public void setLength(double length) {
    //code here
} 

Then your constructor would only be:

那么你的构造函数只会是:

public Shape() {
    //code here
}

This is just one, simple example. In many cases you may want to pass a parameter (or a few) into the constructor depending on the case.

这只是一个简单的例子。在许多情况下,您可能希望根据情况将一个(或几个)参数传递给构造函数。