Java中的声明和定义有什么区别? [英] What is the difference between declaration and definition in Java?
问题描述
我对这两个术语感到很困惑。我检查了stackoverflow,对于C ++有一个类似的问题,但对于java则没有。
I'm very confused between the two terms. I checked on stackoverflow and there's a similar question for C++ but not for java.
有人可以解释java的两个术语之间的区别吗?
Can someone explain the difference between the two terms for java?
推荐答案
概念上的区别很简单:
-
声明:你声明存在某种东西,例如类,函数或变量。你没有说出那个那个类或函数的样子,你只是说它存在。
Declaration: You are declaring that something exists, such as a class, function or variable. You don't say anything about what that class or function looks like, you just say that it exists.
定义:你定义如何实现某些东西,例如类,函数或变量,即你说它实际上是什么
Definition: You define how something is implemented, such as a class, function or variable, i.e. you say what it actually is.
在Java 中,两者之间几乎没有区别,正式来说,声明不仅包括标识符,还有它的定义。以下是我个人对这些术语的详细解释:
In Java, there is little difference between the two, and formally speaking, a declaration includes not only the identifier, but also it's definition. Here is how I personally interpret the terms in detail:
-
类:Java并不是真的与C / C ++一样的单独声明和定义(在头文件和cpp文件中)。您可以在声明它们的位置定义它们。
Classes: Java doesn't really separate declarations and definitions as C/C++ does (in header and cpp files). You define them at the point where you declare them.
函数:当您编写接口(或抽象类)时),你可以说你在宣布一个函数而没有定义它。但是,普通函数总是在声明它们的地方定义。如果您愿意,请将函数体看作其定义。
Functions: When you're writing an interface (or an abstract class), you could say that you're declaring a function, without defining it. Ordinary functions however, are always defined right where they are declared. See the body of the function as its definition if you like.
变量:变量声明看起来像这样:
Variables: A variable declaration could look like this:
int x;
(您声明变量 x
存在且类型为 int
),如果它是局部变量或成员字段。在Java中,没有关于 x
到 define 的信息,除了它应该保留的值,可能由它的赋值决定。
(you're declaring that a variable x
exists and has type int
) either if it's a local variable or member field. In Java, there's no information left about x
to define, except possible what values it shall hold, which is determined by the assignments to it.
以下是我如何使用这些条款的粗略摘要:
Here's a rough summary of how I use the terms:
abstract class SomeClass { // class decl.
// \
int x; // variable decl. |
// |
public abstract void someMethod(); // function decl. |
// |
public int someOtherMethod() { // function decl. |
// | class
if (Math.random() > .5) // \ | def.
return x; // | function definition |
else // | |
return -x; // / |
// |
} // |
} // /
这篇关于Java中的声明和定义有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!