abson abson - 1 year ago 95
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
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download