In Java, a
variable type can be one of five entities:
1. Primitive type;
2. class – A complex type with behavior (API), possibly its implementation, and internal state;
3. enum – An enumeration. A type with a defined finite set of possible values;
4. interface – Only description of behavior, without state. Since Java 8, interfaces can have default implementations. Supports multiple inheritance;
5. @interface – An annotation. Passive class-level meta-information: its presence, parameters, and behavior. Typically used to describe special properties (
@Deprecated), for use by frameworks (
@Test), or development tools (
@NotNull);
Creating new primitives is not
yet possible. A separate
.class
file is created for each reference type during compilation. We will explore its contents later.
Chapter 8 of the specification is dedicated to this topic.
A class can be:
1. Abstract – Marked with the keyword
abstract
. Cannot have instances, may have unimplemented abstract methods, also with the
abstract
modifier and without a body. Similar to a partially implemented interface with state, although from the JVM&s perspective, it is a
completely different entity;
2. Inner (non-static nested) – Declared inside another class. Cannot have static declarations. Has access to all the internals of the host class's
instance. If a member of the host class
foo
is shadowed by a member of the inner class, access to the external can be obtained using the construction
OuterClassname.this.foo
; without shadowing just
foo
works. It is instantiated only from an instance of the host class:
outer.new Inner()
;
3. Nested (inner static) – Has access to all static members of the external class. Otherwise, it does not differ from a regular class;
4. Local – Declared within a method. Is an inner class, in the case of declaration in a static method without access to an instance of the external class. Does not have access modifiers;
5. Anonymous – A local class declared without a name, directly at the point of instantiation, by extending another class or interface. Unlike other nested classes, an anonymous class can extend only one class or interface. Cannot be abstract or final. A lambda expression is a shorthand for creating an object of an anonymous descendant of a
functional interface;
6. Final – With the
final
modifier,
non-extensible;
Inner and nested classes can have several levels of nesting. The modifiers
abstract
and
final
are incompatible, but each is applicable separately to various inner classes (except for anonymous). Different types of nested classes are discussed in detail in the
official tutorial.