skip to content

Classes & Objects

Declaring classes and working with the objects they create — the reference model that every other Java behavior sits on. Interviewers use this area to check you can talk precisely about references versus objects and identity versus equality.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

20

What are the components of a Java class declaration, and what does a minimal class look like?

level: juniorimportance: must knowfreq 70%

answer

  1. [modifiers] class Name [extends] [implements] { body }
  2. Minimal: class Dog {}
  3. Top-level modifiers: public/abstract/final/sealed — NOT private/protected
  4. No extends = implicitly extends Object
  5. Body = fields, methods, constructors, nested types

basics

~20 s

A class declaration is the keyword class, a name, and a body in curly braces holding fields and methods. Optionally it has modifiers (like public) before it and an extends/implements clause. Minimal: class Dog { }.

solid answer

~40 s

A top-level class declaration reads: optional modifiers, the class keyword, the class name, an optional generic type-parameter list, an optional extends clause (one superclass), an optional implements clause (one or more interfaces), then a body in braces. The body holds members: fields, methods, constructors, initializer blocks, and nested types. Legal top-level modifiers are public, final, abstract, sealed/non-sealed, and strictfp; private and protected are not allowed on a top-level class. By convention the name is PascalCase. A minimal valid class is just `class Dog {}` — no modifiers, no superclass (it implicitly extends Object), and an empty body. The compiler supplies a default no-arg constructor when you write none.

go deeper

for a junior

Can write a class with the keyword, a PascalCase name, and braces, and add a field and method.

for a middle

Knows the full clause order (modifiers/extends/implements), which modifiers are legal on a top-level class, and that omitting extends means Object.

for a senior

Explains package-private default access, implicit Object superclass, default-constructor generation, and the role of sealed/abstract/final in expressing design intent.

for a principal

Frames class structure in terms of API surface and encapsulation — chooses modifiers deliberately (final/sealed for closed hierarchies) and can teach the grammar precisely.

## What a class is In Java, a **class** is a blueprint that defines the structure (data) and behavior (methods) of objects. Every piece of code you write lives inside a class (or another type like an interface, enum, or record). Understanding the exact shape of a class declaration is the foundation for everything else in object-oriented Java. ## The grammar of a class declaration A **top-level class** (one written directly in a file, not nested inside another type) has this structure, reading left to right: ``` [modifiers] class Name [<TypeParameters>] [extends Superclass] [implements Interface1, Interface2, ...] { body } ``` Term by term: - **modifiers** — optional keywords that change visibility or behavior. For a top-level class the legal ones are: `public` (visible everywhere), `abstract` (cannot be instantiated, may have unimplemented methods), `final` (cannot be subclassed), `sealed`/`non-sealed` (restrict which classes may extend it, Java 17+), and `strictfp` (a now-rarely-used floating-point flag). You may NOT write `private` or `protected` on a top-level class — those only apply to *members* and *nested* classes. - **class** — the keyword that says "this is a class declaration" (as opposed to `interface`, `enum`, or `record`). - **Name** — the identifier. By the universal Java naming convention it is **PascalCase** (each word capitalized, e.g. `BankAccount`). This is a convention, not a compiler rule, but every codebase and tool expects it. - **<TypeParameters>** — optional generics, e.g. `class Box<T>`, letting the class work with a type supplied later. - **extends Superclass** — optional; names the single class this one inherits from. Java allows only **one** superclass (single inheritance of implementation). If you omit it, the class implicitly extends `java.lang.Object`, the universal root of all classes. - **implements ...** — optional; lists one or more interfaces whose contracts this class promises to fulfill. A class may implement many interfaces. - **{ body }** — curly braces enclosing the **members**: fields (variables that hold state), methods (behavior), constructors (initialization logic), static and instance initializer blocks, and nested types. ## The minimal class The smallest legal class is: ```java class Dog {} ``` This is complete and compiles. It has no modifiers (so it has *package-private* access — visible only within its own package), it implicitly extends `Object`, implements no interfaces, and has an empty body. Because you wrote no constructor, the compiler generates a **default no-argument constructor** for you, so `new Dog()` works. ## A fuller example ```java public final class BankAccount { private long balanceCents; // a field (state) public BankAccount(long opening) { // a constructor this.balanceCents = opening; } public long balanceCents() { // a method (behavior) return balanceCents; } } ``` Here `public` makes it visible everywhere, `final` forbids subclassing, the body holds one field, one constructor, and one method. ## Why this matters Knowing the precise anatomy lets you read any class at a glance, predict its visibility and inheritance, and avoid compiler errors like applying `private` to a top-level class. It also clarifies what is mandatory (the keyword, name, and braces) versus optional (everything else).

  • What access does `class Dog {}` have with no modifier?
    Package-private (default): visible only to other code in the same package.
  • What happens if you write no constructor at all?
    The compiler generates a default public no-arg constructor (with the same access as the class), so `new Dog()` works — unless you declare any other constructor, in which case it is not generated.

saying these in an interview costs you the question

  • Saying a top-level class can be private or protected
  • Claiming the class keyword or braces are optional
  • Thinking a class with no extends has no superclass (it has Object)
  • Confusing modifiers with the class name order

context

open as a page

Explain the one-public-class-per-file rule and how a .java file's name relates to its classes.

level: juniorimportance: must knowfreq 68%

basics

~20 s

A single .java file can have at most one public top-level class, and the file must be named exactly after that public class (plus .java). You can add more non-public (package-private) classes in the same file.

open as a page

In Java, what is the difference between == and the equals() method when comparing two object references?

level: juniorimportance: must knowfreq 90%

basics

~10 s

== checks if two references point to the exact same object in memory (identity). equals() checks whether two objects are logically equal in value. They can disagree: two different objects can hold equal data.

open as a page

What does the `new` keyword do in Java when you create an object?

level: juniorimportance: must knowfreq 78%

basics

~20 s

new makes a fresh object. It sets aside memory on the heap for the object, runs its constructor to set it up, and gives you back a reference (an address) you store in a variable.

open as a page

Explain the difference between a reference variable and the object it points to in Java.

level: juniorimportance: must knowfreq 80%

basics

~20 s

A reference variable is like a label that holds the address of an object; the object is the actual data living on the heap. Many labels can point to the same object, and a label can point to nothing (null).

open as a page

How is `this` used to disambiguate an instance field from a same-named constructor or method parameter, and what happens if you forget it?

level: juniorimportance: must knowfreq 75%

basics

~20 s

When a parameter has the same name as a field, the parameter hides the field. Writing this.field = field assigns the parameter to the field. Forgetting this just assigns the parameter to itself and the field stays unchanged.

open as a page

What does the keyword `this` refer to inside a Java instance method or constructor?

level: juniorimportance: must knowfreq 70%

basics

~10 s

this refers to the current object — the specific instance whose method or constructor is running. It lets that object refer to its own fields and methods.

open as a page

When does an object become eligible for garbage collection in Java, and what makes it eligible?

level: middleimportance: must knowfreq 72%

basics

~20 s

An object becomes eligible for garbage collection when it is no longer reachable from any live part of the running program — nothing holds a reference to it anymore. Setting all references to it to null or letting them go out of scope makes it unreachable.

open as a page

Is Java pass-by-value or pass-by-reference? Explain what happens when you pass an object to a method.

level: middleimportance: must knowfreq 85%

basics

~20 s

Java is always pass-by-value. For objects, the value copied is the reference, so the method can change the object's fields (the caller sees it), but reassigning the parameter to a new object does not affect the caller's variable.

open as a page

How does object identity differ from object equality, and how do `==`, `equals()`, and `hashCode()` relate for instantiated objects?

level: seniorimportance: must knowfreq 75%

basics

~20 s

Identity asks 'is this the exact same object?' and is tested with == on references. Equality asks 'do these represent the same value?' and is tested with equals(). Two different objects can be equal by value but never identical.

open as a page

How do you compare two object references for value equality safely when either might be null, and why is x.equals(y) risky?

level: juniorimportance: should knowfreq 60%

basics

~10 s

Calling x.equals(y) throws NullPointerException if x is null. Use Objects.equals(x, y) instead — it handles nulls (both null returns true, one null returns false) and otherwise calls x.equals(y).

open as a page

Within a .java source file, what is the required order of the package statement, imports, and type declarations?

level: middleimportance: should knowfreq 45%

basics

~10 s

A source file has up to one package statement first, then any import statements, then the class (and other type) declarations. The package line must come before imports, and imports before any class.

open as a page

What is the difference between a top-level class and a nested class, and what kinds of nested classes does Java have?

level: middleimportance: should knowfreq 58%

basics

~20 s

A top-level class is declared directly in a file. A nested class is declared inside another class. Java has four nested kinds: static nested classes, inner (non-static) classes, local classes (inside a method), and anonymous classes.

open as a page

Why can comparing strings with == sometimes return true and sometimes false, and what role does the string pool (interning) play?

level: middleimportance: should knowfreq 75%

basics

~20 s

String literals are stored once in a shared pool, so two equal literals point to the same object and == is true. Strings made with new (or computed at runtime) are separate objects, so == is false. Always use equals() to compare string contents.

open as a page

What does it mean to pass `this` as an argument to another method or constructor, and what are common uses and pitfalls?

level: middleimportance: should knowfreq 55%

basics

~20 s

Passing this hands a reference to the current object to other code, so it can call back or store the object. Common in registering listeners or builder chaining. The pitfall is sharing the object before it is fully built.

open as a page

What kinds of members can a class body contain, and which modifiers apply to members but not to a top-level class?

level: seniorimportance: should knowfreq 40%

basics

~10 s

A class body can hold fields, methods, constructors, initializer blocks, and nested types. Members can use private and protected and static, which are not allowed on a top-level class.

open as a page

When should a class be compared by identity (==) versus by logical equality (equals()), and how does that map to entity vs value object modeling?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Use identity (==) for objects that represent a unique thing with a lifecycle (entities) — two are the same only if they're literally the same object. Use equals() (value comparison) for objects defined purely by their data (value objects), like money or a date.

open as a page

Walk through the full lifecycle of a Java object from creation to memory reclamation.

level: seniorimportance: should knowfreq 58%

basics

~20 s

An object is created with new (memory allocated, fields defaulted, constructor run), used while reachable through references, becomes eligible for GC when no longer reachable, then is collected and its memory reclaimed at some later time.

open as a page

How does `this` relate to `super`, and is the `this` seen inside an inherited method the subclass object or the superclass part?

level: seniorimportance: should knowfreq 45%

basics

~20 s

There is only one object. this always refers to that whole object (the actual runtime subclass instance), even inside an inherited superclass method. super is not a different object — it just accesses the parent's version of members on the same this.

open as a page

If a class overrides equals() and hashCode() to compare by value, how can you still test for true object identity, and where does System.identityHashCode fit in?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

Use == to test whether two references point to the same object — overriding equals() never changes what == does. System.identityHashCode(x) gives the original identity-based hash even when hashCode() is overridden, and IdentityHashMap compares keys by ==.

open as a page