Java 中的方法与构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19061599/
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
Methods vs Constructors in Java
提问by nckbrz
I have just started programming with 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?
我刚刚开始用 Java 编程。在谈论方法和构造函数时,我们使用的文本是缺乏的。我不确定方法或构造函数到底是什么,以及是什么使每个方法或构造函数独一无二。有人可以帮我定义它们并区分两者吗?
采纳答案by rgettman
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. Methods can be called directly on an object that has already been created with new
.
不能直接调用构造函数;当new
关键字创建对象时,它们会被隐式调用。可以直接在已使用new
.
The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. 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
.
回答by nckbrz
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.
构造函数是一种特殊的方法,它允许您创建类的新实例。它涉及初始化逻辑。
回答by Hot Licks
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.
“方法”是“子程序”是“过程”是“函数”是“子程序”是......相同的概念有许多不同的名称,但基本上是一个命名的代码段,你可以“调用”来自其他一些代码。通常,代码以某种方式整齐地打包,带有某种给出其名称和参数的“标题”以及由BEGIN
&END
或{
&}
或诸如此类的“正文” 。
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> )
。)
回答by Alex Mohr
In Java, classes you write are Objects. Constructors construct those objects. For example if I have an Apple.class
like so:
在 Java 中,您编写的类是对象。构造函数构造这些对象。例如,如果我有一个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.
希望我在代码的注释中解释了所有内容,但这里有一个摘要:构造函数“构造”一个类类型的对象。构造函数必须与类命名相同。它们主要用于初始化实例变量方法是对象的功能。
回答by naved
the difference r
:
区别r
:
- Constructor must have the name same as class but method can be made by any name.
- Constructor are not inherited automatically by child classes while child inherit method from their parent class unless they r protected by private keyword.
- Constructor
r
called explicitly while methods implicitaly. - Constructor doesnot have any return type while method have.
- 构造函数必须与类同名,但方法可以使用任何名称。
- 构造函数不会被子类自动继承,而子类从其父类继承方法,除非它们受到 private 关键字的保护。
- 构造函数
r
显式调用,而方法隐式调用。 - 构造函数没有任何返回类型,而方法有。
回答by geetha
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.
构造函数不允许任何返回类型,方法允许返回类型。
回答by OrangeDeb
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...
构造函数与方法有何不同?让我来计算一下...
Constructors must be invoked with the
new
operator while methods may not be invoked with thenew
operator. Related: Constructors may not be called by name while methods must be called by name.Constructors may not have a return type while methods must have a return type.
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:
public class MyClass { public MyClass() { } // constructor public String MyClass() { return "MyClass() method"; } // method }
Constructors may initialize instance constants while methods may not.
Public and protected constructors are not inherited while public and protected methods are inherited.
Constructors may call the constructors of the super class or same class while methods may not call either super() or this().
必须使用
new
运算符调用构造函数,而不能使用new
运算符调用方法。相关:构造函数不能按名称调用,而方法必须按名称调用。构造函数可能没有返回类型,而方法必须有返回类型。
如果方法与类同名,则它必须具有返回类型。否则,它是一个构造函数。在同一个类定义中可以有两个MyClass()签名的事实应该使所有构造函数和方法都是不同的实体:
public class MyClass { public MyClass() { } // constructor public String MyClass() { return "MyClass() method"; } // method }
构造函数可以初始化实例常量,而方法则不能。
公共和受保护的构造函数不被继承,而公共和受保护的方法是被继承的。
构造函数可以调用超类或同一个类的构造函数,而方法不能调用 super() 或 this()。
So, what is similar about methods and constructors?
那么,方法和构造函数有什么相似之处呢?
They both have parameter lists.
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.
至于具有相同可见性修饰符的构造函数和方法……字段和方法有更多的共同可见性修饰符。
Constructors may be: private, protected, public.
Methods may be: private, protected, public, abstract, static, final, synchronized, native, strictfp.
Data fields may be: private, protected, public, static, final, transient, volatile.
构造函数可以是:private、protected、public。
方法可能是:private、protected、public、abstract、static、final、synchronized、native、 strictfp。
数据字段可能是:private、protected、public、static、final、transient、volatile。
In Conclusion
综上所述
In Java, the form and function of constructors is significantly different than for methods. 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 中,构造函数的形式和功能与方法明显不同。因此,将它们称为专门的方法实际上会使新程序员更难了解差异。它们比相似的更不同,学习它们作为不同的实体在 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. But, in Java, constructors are not methods at all, much less specialized methods.
我确实认识到 Java 在这方面不同于其他语言,即 C++,其中专用方法的概念起源于语言规则并得到语言规则的支持。但是,在 Java 中,构造函数根本不是方法,更不是专门的方法。
Even javadoc recognizes the differences between constructors and methods outweigh the similarities; and provides a separate section for constructors.
甚至 javadoc 也认识到构造函数和方法之间的差异大于相似之处;并为构造函数提供了一个单独的部分。
回答by murthy naika k
The main difference is
主要区别是
1.Constructorare used to initialize the state of object,where as methodis expose the behaviour of object.
1.构造函数用于初始化对象的状态,方法是暴露对象的行为。
2.Constructormust not have return type where as methodmust have return type.
2.构造函数不能有返回类型,方法必须有返回类型。
3.Constructorname same as the class name where as methodmay or may not the same class name.
3.构造函数名称与类名称相同,其中方法可能与类名称相同,也可能不同。
4.Constructorinvoke implicitly where as methodinvoke explicitly.
4.构造函数隐式调用,方法调用显式。
5.Constructorcompiler provide default constructor where as methodcompiler does't provide.
5.构造函数编译器提供默认构造函数,而方法编译器不提供。
回答by Arindam Sarkar
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. In that case constructor always come first to instantiate Class here class Diff().
所以,这里只显示构造函数方法 Diff() 语句,因为我们创建了 Diff 类对象。在这种情况下,构造函数总是首先在此处实例化 Class Diff()。
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.
构造函数完成了它的工作,然后方法来了并完成了它的真正实现。
In this program when we call
在这个程序中当我们调用
ob.print();
then method will coming.
那么方法就来了。
Thanks
谢谢
Arindam
阿林丹
回答by sachin dubey
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. Methods performs operations on objects that already exist. In other words, to call a method we need an object of the class.
2:构造函数初始化类的对象,而方法不初始化。方法对已经存在的对象执行操作。换句话说,要调用一个方法,我们需要一个类的对象。
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");
}
}