java中定义与声明的区别,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.

Can someone explain the difference between the two terms for java?

解决方案

The conceptual difference is simple:

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.

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:

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;

(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; // / |

// |

} // |

} // /

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值