skip to content

Object-Oriented Programming

How Java actually implements objects: classes, constructors, access modifiers, extends and interfaces, dispatch, plus the newer modelling tools (records, sealed types, pattern matching) and the java.lang.Object contracts. Interviewers spend more time here than anywhere else because these mechanics decide whether your code compiles, dispatches, and hashes the way you expect.

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

explore

questions

263 · 15 sections

How does Java implement encapsulation, and why is hiding fields behind accessors more than just a convention?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Java hides an object's data by marking fields private and exposing them through public getter and setter methods. This lets the class control and validate access and change its internals later without breaking other code.

open as a page

What are the four pillars of object-oriented programming, and how does Java realize each one in concrete language features?

level: juniorimportance: must knowfreq 88%
basics
~10 s

The four pillars are encapsulation, inheritance, polymorphism, and abstraction. Java uses access modifiers for encapsulation, extends and interfaces for inheritance, method overriding for polymorphism, and abstract classes and interfaces for abstraction.

open as a page

Explain dynamic method dispatch (late binding) in Java: what is bound at compile time versus runtime, and how does it differ from overloading?

level: middleimportance: must knowfreq 78%
basics
~20 s

When you call an overridden method, Java decides at runtime which version to run based on the object's actual type, not the variable's declared type. This is dynamic dispatch. Overloading is different: the compiler picks among same-named methods at compile time using the argument types.

open as a page

In Java's OOP model, when would you choose an abstract class over an interface (or vice versa), and what does each let you do that the other cannot?

level: middleimportance: should knowfreq 74%
basics
~20 s

Use an interface to define a pure capability that many unrelated classes can implement, since a class can implement many interfaces. Use an abstract class when you need shared state (fields) or a partial implementation, since a class can extend only one.

open as a page

Java enforces single inheritance of implementation but multiple inheritance of type. What problems does this design solve and create, and how do modern Java features and principles like 'composition over inheritance' address its limits?

level: seniorimportance: should knowfreq 55%
basics
~20 s

Allowing a class to extend only one class avoids ambiguity when two parents have conflicting code (the diamond problem), while letting a class implement many interfaces keeps flexibility. The downside is rigid hierarchies, which Java teams usually solve by favoring composition (holding objects and delegating) over deep inheritance.

open as a page

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

level: juniorimportance: must knowfreq 70%
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 { }.

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

What are the components of a Java method declaration, and what does each part do?

level: juniorimportance: must knowfreq 78%
basics
~20 s

A method has modifiers (like public, static), a return type (the kind of value it gives back, or void for none), a name, a parameter list in parentheses, an optional throws clause, and a body in braces with the code.

open as a page

What is method overloading in Java, and what makes two methods valid overloads of each other?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Method overloading is having several methods with the same name in the same class but different parameter lists (different number or types of parameters). The compiler picks the right one based on the arguments you pass.

open as a page

Is Java pass-by-value or pass-by-reference? Explain what actually gets passed when you call a method.

level: juniorimportance: must knowfreq 88%
basics
~10 s

Java is always pass-by-value. The method gets a copy of the argument. For an object, that copy is a copy of the reference (the address), not a copy of the object itself.

open as a page

What is recursion in Java, and why must a recursive method have a base case?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Recursion is when a method calls itself to solve a smaller piece of a problem. The base case is the simple input that stops the calling, so the method does not call itself forever and eventually returns an answer.

open as a page

What are varargs in Java? Show the syntax and explain how the method receives its arguments.

level: juniorimportance: must knowfreq 70%
basics
~20 s

Varargs (variable arguments) let a method accept any number of arguments of one type, written as Type... name. Inside the method, name is an array. You call it like sum(1, 2, 3) or pass an array.

open as a page

In what order do constructors execute when you create an object whose class extends another class? Walk through what happens from the `new` call down to the body of your constructor.

level: juniorimportance: must knowfreq 68%
basics
~10 s

The parent constructor runs before the child constructor body. So construction goes top-down: the topmost ancestor (Object) is built first, then each subclass in turn, ending with the class you actually created.

open as a page

What is constructor chaining in Java, and how do this() and super() participate in it?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Constructor chaining means one constructor calls another so you don't repeat setup. this(...) calls another constructor in the same class; super(...) calls the parent class's constructor.

open as a page

Are constructors inherited in Java? Explain how subclass construction actually works.

level: juniorimportance: must knowfreq 65%
basics
~20 s

No. Constructors are not inherited. A subclass must define its own constructors. When a subclass object is built, its constructor first calls a superclass constructor (with super(...), or an implicit super() if you omit it).

open as a page

What is a constructor in Java, and what is the implicit default constructor?

level: juniorimportance: must knowfreq 80%
basics
~20 s

A constructor is a special method that runs when you create an object with new, to set it up. If you write no constructor, Java adds a hidden no-argument one for you so you can still write new MyClass().

open as a page

When does the Java compiler NOT generate the default no-arg constructor, and what problem can that cause?

level: middleimportance: must knowfreq 78%
basics
~20 s

As soon as you write any constructor of your own — even one that takes parameters — the compiler stops adding the free no-arg one. Then new MyClass() won't compile unless you also write the no-arg constructor yourself.

open as a page

Java lets you make a field public, so why does encapsulation favor private fields with accessor methods?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A private field hides the data and lets the class control how it's read or changed through methods. That means you can add validation, compute values, or change how the data is stored later without breaking code that uses the class.

open as a page

What are the four access levels in Java and what does each one mean?

level: juniorimportance: must knowfreq 85%
basics
~20 s

Java has four access levels: public (everywhere), private (only inside the same class), protected (same package plus subclasses), and default — written by adding no keyword — which allows access only inside the same package.

open as a page

What is information hiding in Java, and how do you apply it to a class?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Information hiding means keeping a class's internal data private and letting outside code touch it only through public methods. In Java you mark fields private and add public getters/setters so the class controls how its state is read and changed.

open as a page

Walk through the access matrix: for each access level, who can access the member — same class, same package, subclass in another package, and unrelated code in another package?

level: middleimportance: must knowfreq 78%
basics
~10 s

private: same class only. Default (no keyword): same package. protected: same package plus subclasses anywhere. public: everyone. Each level adds one more group of allowed callers.

open as a page

Why can a getter or setter that exposes a mutable internal object break information hiding, and how do you fix it?

level: middleimportance: must knowfreq 60%
basics
~20 s

If a getter returns the actual internal mutable object (like a List or Date), callers can change it from outside, bypassing your class's rules. The fix is to return or store a copy (a defensive copy), or hand back an unmodifiable view, so the internal state stays under the class's control.

open as a page

What does the extends keyword do in Java, and what does it mean that Java only allows single class inheritance?

level: juniorimportance: must knowfreq 85%
basics
~10 s

extends makes one class a subclass of another, so the subclass inherits the parent's fields and methods. Java allows a class to extend only one direct parent class (single inheritance).

open as a page

How do you call a parent class's overridden method from a subclass, and what does super refer to?

level: juniorimportance: must knowfreq 80%
basics
~10 s

Use super.methodName() to call the parent's version of a method that the subclass has overridden. super refers to the parent-class part of the current object.

open as a page

What does the `final` keyword do when applied to a class versus a method in Java?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A final class can't be extended (no subclasses). A final method can't be overridden by a subclass, though the class itself can still be subclassed. Both lock down a piece of behavior so others can't change it.

open as a page

What conditions must a subclass method satisfy to override a method inherited from its superclass?

level: juniorimportance: must knowfreq 80%
basics
~20 s

The subclass method must have the same name and same parameter list as the superclass method, and the same (or a compatible) return type. If the name or parameters differ, it is not an override - it becomes a separate or overloaded method.

open as a page

How does super() work in constructors, and what are the rules for constructor chaining in an inheritance hierarchy?

level: middleimportance: must knowfreq 78%
basics
~10 s

super(...) calls a parent constructor and must be the first statement in a subclass constructor. If you don't write it, Java inserts a no-arg super() automatically so the parent is always initialized first.

open as a page

What is the difference between upcasting and downcasting in Java, and which one is implicit?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Upcasting treats an object as one of its parent types (Dog seen as Animal); it is automatic and always safe. Downcasting treats it back as the more specific child type (Animal back to Dog); it needs an explicit cast and can fail at runtime.

open as a page

What is the difference between method overloading and method overriding in Java, and which kind of polymorphism does each represent?

level: juniorimportance: must knowfreq 88%
basics
~20 s

Overloading means several methods share a name but take different parameters; the compiler picks one. Overriding means a subclass replaces a parent method with the same signature; Java picks it at runtime based on the real object. Overloading is compile-time polymorphism, overriding is runtime polymorphism.

open as a page

What is the difference between static (early) binding and dynamic (late) binding in Java, and when does each happen?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Binding is how a call is matched to the actual method or variable. Static binding is decided at compile time (overloaded methods, static methods, fields). Dynamic binding is decided at run time based on the real object type, which is how overridden instance methods work.

open as a page

How do you safely downcast a reference, and what does the instanceof operator give you (including pattern matching)?

level: middleimportance: must knowfreq 68%
basics
~20 s

Before casting a parent-typed reference to a child type, check it with instanceof. If the check passes, the cast is safe. Modern Java lets you do both at once: if (x instanceof Dog d) binds d so you skip the separate cast.

open as a page

How does the JVM resolve an overridden method call at runtime? Explain dynamic method dispatch.

level: middleimportance: must knowfreq 74%
basics
~20 s

Each object knows its real class. When you call an overridden method through a parent-type reference, the JVM looks up the method on the object's actual class at runtime and runs that version. This runtime lookup is called dynamic method dispatch.

open as a page

How do you declare an abstract method, and what obligations does it place on subclasses?

level: juniorimportance: must knowfreq 70%
basics
~20 s

An abstract method is written with the abstract keyword and no body — just a signature ending in a semicolon. Any concrete (non-abstract) subclass must override it and supply a real body, or it won't compile.

open as a page

What is an abstract class in Java, and what can it contain that a regular interface (historically) could not?

level: juniorimportance: must knowfreq 78%
basics
~20 s

An abstract class is a class marked with the abstract keyword that you cannot create objects from directly. It can mix finished methods with unfinished (abstract) methods that subclasses must complete. It can also hold normal fields and constructors.

open as a page

How do you declare an interface in Java, and what can it contain?

level: juniorimportance: must knowfreq 75%
basics
~20 s

You write interface Name { ... }. An interface lists method signatures (no bodies) that implementing classes must provide, and it can hold constants. A class uses implements Name to promise it provides those methods.

open as a page

What are default methods in a Java interface, why were they added, and how do you declare one?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A default method is an interface method with a body, marked with the default keyword. Classes that implement the interface inherit it for free, so you can add new methods to an interface without breaking existing implementers.

open as a page

What is a functional interface in Java, and what does the @FunctionalInterface annotation do?

level: juniorimportance: must knowfreq 78%
basics
~20 s

A functional interface is an interface with exactly one abstract method, so it can be implemented by a lambda. @FunctionalInterface is an optional annotation that makes the compiler check that the interface really has just one abstract method.

open as a page

What is the difference between a HAS-A and an IS-A relationship in Java, and how does each show up in code?

level: juniorimportance: must knowfreq 70%
basics
~20 s

IS-A means one type is a kind of another (a Car IS-A Vehicle) and uses inheritance (extends). HAS-A means an object holds another as a part (a Car HAS-A Engine) and uses a field. IS-A is inheritance; HAS-A is composition.

open as a page

What does 'favor composition over inheritance' mean in Java, and why is it a recommended default?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Instead of one class extending another to reuse code, the class holds another object as a field and calls its methods. It is preferred because it couples classes less tightly and is more flexible to change.

open as a page

Within HAS-A relationships, how do composition and aggregation differ in terms of ownership and lifecycle?

level: middleimportance: must knowfreq 65%
basics
~20 s

Both are HAS-A. Composition is strong ownership: the part can't live without the whole, and when the whole is destroyed, so is the part (a House HAS rooms). Aggregation is weak: the part can exist independently and may be shared (a Team HAS players who outlive the team).

open as a page

How do you implement reuse via the delegation pattern in Java? Show held fields and forwarding methods.

level: middleimportance: must knowfreq 62%
basics
~10 s

Keep the other object in a private field, and write methods that simply call the matching method on that held object. Those one-line pass-through methods are the forwarding methods.

open as a page

When you compose a mutable object inside a class, what goes wrong without defensive copying, and how do you fix it?

level: seniorimportance: should knowfreq 55%
basics
~20 s

If you store a caller's mutable object directly, the caller still holds a reference and can change your object's internals behind your back. Fix it by copying the object when it comes in (constructor/setter) and when it goes out (getter), so outside code can't reach the part you own.

open as a page

What is an inner (non-static) class in Java, and how does it differ from a static nested class?

level: juniorimportance: must knowfreq 72%
basics
~20 s

An inner class is a non-static class defined inside another class. Each inner-class object is tied to an object of the outer class and can use the outer object's fields and methods. A static nested class has no such tie.

open as a page

What is a static nested class in Java, and how do you declare one?

level: juniorimportance: must knowfreq 70%
basics
~10 s

A static nested class is a class declared inside another class with the static keyword. You can create and use it without first creating an object of the outer class: new Outer.Nested().

open as a page

What does it mean that a local or anonymous class can only capture effectively-final local variables, and why does Java impose this rule?

level: middleimportance: must knowfreq 68%
basics
~20 s

A local variable used inside a local/anonymous class must never be reassigned after it's set — that's what 'effectively final' means. Java requires this because the class captures a copy of the variable's value, so allowing reassignment would let the two copies drift apart.

open as a page

What is the key difference between a static nested class and a (non-static) inner class regarding the enclosing instance?

level: middleimportance: must knowfreq 78%
basics
~20 s

A non-static inner class secretly holds a reference to the outer object that created it, so it can use the outer object's fields. A static nested class holds no such reference, so it can't reach the outer instance's fields and needs no outer object to be created.

open as a page

What is a local class and what is an anonymous class in Java, and how do they differ?

level: juniorimportance: should knowfreq 55%
basics
~20 s

A local class is a named class declared inside a method body. An anonymous class is a one-time, unnamed class you declare and instantiate in a single expression, usually to implement an interface or extend a class on the spot.

open as a page

What is an enum in Java, and how do you declare one with a fixed set of constants?

level: juniorimportance: must knowfreq 80%
basics
~20 s

An enum is a special class whose instances are a fixed, named set of constants. You declare it with the enum keyword and list the constants, e.g. enum Day { MONDAY, TUESDAY }. Each constant is one shared, type-safe object.

open as a page

How do you use an enum in a Java switch statement, and what conveniences does switching on an enum give you?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Put the enum value in switch(value) and use the bare constant names (like MONDAY, not Day.MONDAY) in each case. The compiler knows the type, so you skip the prefix and it can warn if a case is missing.

open as a page

How do you add fields, a constructor, and methods to an enum, and why is the constructor implicitly private?

level: middleimportance: must knowfreq 70%
basics
~20 s

List each constant with constructor arguments in parentheses, then declare instance fields, a constructor, and methods after a semicolon. The constructor is implicitly private because you may not create new enum instances — the JVM creates them all at load time.

open as a page

What do the built-in enum methods values(), valueOf(), name(), and ordinal() do, and what are their costs and caveats?

level: middleimportance: must knowfreq 72%
basics
~20 s

values() returns an array of all constants in declaration order. valueOf("NAME") returns the constant with that exact name (throws if none). name() returns the constant's declared name as a String. ordinal() returns its zero-based position in the declaration list.

open as a page

Why is a single-element enum considered the best way to implement a singleton in Java?

level: seniorimportance: must knowfreq 60%
basics
~20 s

Because the JVM guarantees exactly one instance of each enum constant, and that single instance survives reflection and serialization attacks for free. So enum Singleton { INSTANCE; } gives you a thread-safe, attack-proof singleton with no boilerplate.

open as a page

What is a Java record, and what does the compiler generate for you from its components?

level: juniorimportance: must knowfreq 78%
basics
~20 s

A record is a compact class for holding immutable data. You list its components in the header, and the compiler auto-generates a private final field plus an accessor for each, a constructor, and equals, hashCode, and toString.

open as a page

What is the canonical constructor of a Java record, and what does the compiler generate if you don't write one?

level: juniorimportance: must knowfreq 70%
basics
~20 s

The canonical constructor is a record's main constructor whose parameters match its components, one-for-one, by name and type. If you don't write one, the compiler generates it for you, and it just assigns each parameter to the matching field.

open as a page

What members can you add to a Java record, and what is forbidden?

level: juniorimportance: must knowfreq 78%
basics
~20 s

You can add instance methods, static fields, static methods, and nested types. You can also override the auto-generated accessors, equals, hashCode, and toString. You cannot declare extra instance fields beyond the ones in the record header.

open as a page

How does a record's generated equals, hashCode, and toString behave, and what is the resulting equality contract?

level: middleimportance: must knowfreq 70%
basics
~20 s

Two records are equal if they are the same record type and every component is equal. hashCode is computed from all components and stays consistent with equals. toString prints the type name and each component, like Point[x=1, y=2].

open as a page

What is a compact canonical constructor in a Java record, and how does field assignment work in it?

level: middleimportance: must knowfreq 72%
basics
~20 s

A compact constructor uses the record's name with no parameter list and no field assignments. You write only validation or cleanup code; the compiler automatically assigns all the components to their fields at the very end.

open as a page

What is a sealed class or interface in Java, and what problem does it solve?

level: juniorimportance: must knowfreq 72%
basics
~10 s

A sealed class or interface restricts which other classes can extend or implement it. You list the allowed subtypes with the permits clause, so no unexpected class can join the hierarchy.

open as a page

Every direct subtype of a sealed class must itself declare one of three modifiers - which three, and what does each mean?

level: middleimportance: must knowfreq 68%
basics
~10 s

Each permitted subclass must be final (no further subclasses), sealed (continues the closed hierarchy with its own permits list), or non-sealed (reopens that branch so anyone can extend it).

open as a page

What does it mean for a switch over a sealed type to be exhaustive, and how does a sealed hierarchy let the compiler verify exhaustiveness without a default arm?

level: middleimportance: must knowfreq 55%
basics
~20 s

A sealed type lists exactly which subtypes can exist. If your switch has a case for every permitted subtype, the compiler knows nothing else is possible and accepts it as complete (exhaustive) without a default branch.

open as a page

What are the location/accessibility constraints on a sealed type and its permitted subtypes (same module/package, etc.), and why do they exist?

level: seniorimportance: should knowfreq 52%
basics
~20 s

A sealed type and all its permitted subtypes must live together: in a named module, in the same module; otherwise in the same package. Each permitted subtype must directly extend the sealed type and be accessible to it at compile time.

open as a page

Why might you deliberately avoid writing a default arm in a switch over a sealed type, even though default would make the switch compile?

level: seniorimportance: should knowfreq 48%
basics
~20 s

Leaving out default makes the compiler force you to handle every subtype. If you add a new subtype later, the switch stops compiling and shows you exactly where to update it. A default would hide that.

open as a page

What is the instanceof pattern matching feature in Java, and how does it improve on the classic instanceof-then-cast idiom?

level: juniorimportance: must knowfreq 70%
basics
~20 s

instanceof pattern matching lets you test a type and bind the value to a typed variable in one step: if (obj instanceof String s) gives you s already cast to String, so you skip the separate, manual cast.

open as a page

What is switch pattern matching in Java, and how do type patterns in case labels differ from the traditional constant-based switch?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Switch pattern matching lets each case test the type of the value instead of comparing it to a constant. A type pattern like case Circle c matches when the value is a Circle and binds it to c, which you can use directly in that branch.

open as a page

Explain flow scoping for instanceof pattern variables. Where is the binding variable in scope, and why does it work after && but not after ||?

level: middleimportance: must knowfreq 60%
basics
~20 s

The pattern variable is in scope only where the compiler is sure the match was true. After && the match must hold for the right side to run, so it's usable there; after || the right side runs precisely when the match failed, so it isn't.

open as a page

How does a sealed type hierarchy let a switch expression be exhaustive without a default arm, and why is omitting default sometimes preferable?

level: seniorimportance: must knowfreq 55%
basics
~20 s

A sealed type lists all its permitted subtypes, so the compiler knows the complete set of possibilities. If your switch has an arm for each one, it covers everything and you can skip default. Omitting default means adding a new subtype later causes a compile error, reminding you to handle it.

open as a page

What is a record deconstruction pattern in Java, and how does it differ from a plain type pattern?

level: juniorimportance: should knowfreq 55%
basics
~20 s

A record pattern matches a record and pulls its components into variables in one step. Instead of binding the whole record like 'Point p', you write 'Point(int x, int y)' to get x and y directly without calling p.x() and p.y().

open as a page

What is the Comparable interface in Java and what does its compareTo method return?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Comparable defines a type's natural ordering through one method, compareTo. It returns a negative number if this object is smaller, zero if equal in order, and a positive number if larger.

open as a page

What does the default Object.equals() method compare, and how does that differ from the == operator?

level: juniorimportance: must knowfreq 78%
basics
~10 s

By default, equals() checks whether two references point to the exact same object in memory — the same as ==. To compare by value (content), you must override equals() yourself.

open as a page

Walk through how you implement equals() for a Java class. What checks do you perform, and in what order?

level: juniorimportance: must knowfreq 80%
basics
~20 s

First check if the other object is the same one (==). Then check it isn't null and is the right type. Then cast it and compare each field that defines equality, using Objects.equals for object fields so nulls are handled safely.

open as a page

Why must you override hashCode() whenever you override equals() in Java?

level: juniorimportance: must knowfreq 90%
basics
~20 s

Because Java's hash-based collections (like HashMap and HashSet) first use hashCode() to find the right bucket, then equals() to compare. If equal objects return different hash codes, they land in different buckets and the collection never finds the match.

open as a page

What is the hashCode() contract in Java? State its rules.

level: juniorimportance: must knowfreq 82%
basics
~20 s

hashCode() returns an int for an object. Two rules matter: if two objects are equal (equals() is true), they must return the same hashCode; and a hashCode must stay the same across repeated calls during one run. Unequal objects may share a code.

open as a page