I faced a rather simple question in an interview
Why do we use class keyword for declaring classes? Could anyone just tell me as to how to answer it?
I faced a rather simple question in an interview
Why do we use class keyword for declaring classes? Could anyone just tell me as to how to answer it?
To separate it from interfaces/methods, thereby saying that there is a possiblity that it can be instantiated somewhere else (if it is not abstract etc).
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
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.
Because it's a lot simpler for the compiler to validate source code against the grammar for valid syntax allowed in a class versus valid syntax allowed in an interface/enum/attribute definition if you explicitly give it this information, rather than the compiler having to have the intelligence to infer this.
To better resolve ambiguity. A .java file can either be an interface, an enum or a class. How would you,for example distinguish between an interface
and an abstract class
with no method bodies?
The Java compiler simply doesn't work that way - i.e. go through the declaration and then see what it could possibly be. Not saying it can't, it's just designed that way.
The reason is simply for readability.
class
keyword.enum
keyword.interface
keyword.Keywords play very important role in a computer language, and the more explicit and obvious its meanings are, the better. Naming them inconsistently would do more harm than good.
The full list of keywords is given in the Java Language Specification:
The following character sequences, formed from ASCII letters, are reserved for use as keywords and cannot be used as identifiers:
abstract continue for new switch assert default if package synchronized boolean do goto private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const float native super while
The keywords
const
andgoto
are reserved, even though they are not currently used.