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?
Answer
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 typeint
) either if it’s a local variable or member field. In Java, there’s no information left aboutx
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; // / | // | } // | } // /