abson abson - 7 months ago 39
Java Question

Keyword "class" in declaration

I faced a rather simple question in an interview.

Why do we use the

keyword for declaring classes?

Oak Oak

Short answer: because that's the way it's done in C++. Java has taken the bulk of its syntax from C++ - a wise decision, in my opinion, as it really helped with drawing programmers when it was still new.

Now, if your question is why a keyword is needed at all - i.e. why can't the compiler just deduce where classes are declared - maybe it can, but using a keyword has the benefits of

  1. Being easier to compile.
  2. Being more readable to humans than implicit declarations.
  3. As I said above - being similar to C++ syntax.

EDIT: one other things - some things simply cannot be deduced by the compiler in the Java syntax - for example, the only difference between an empty class and an empty interface (both legal in Java) is the class / interface keyword.