I faced a rather simple question in an interview.
Why do we use the class
keyword for declaring classes?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With