[{"data":1,"prerenderedAt":123},["ShallowReactive",2],{"qa-\u002Fjava\u002Foop\u002Fclasses-objects":3},{"page":4,"siblings":103,"blog":120},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"questionsCount":93,"related":94,"seo":95,"seoDescription":96,"stem":97,"subtopic":98,"topic":99,"topicSlug":100,"updated":101,"__hash__":102},"qa\u002Fjava\u002Foop\u002Fclasses-objects.md","Classes Objects",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"easy","md","Java","java",{},true,1,"\u002Fjava\u002Foop\u002Fclasses-objects",[23,27,31,35,39,43,48,52,56,60,64,68,72,76,81,85,89],{"id":24,"difficulty":14,"q":25,"a":26},"class-vs-object","What is the difference between a class and an object?","A **class** is a *blueprint* — it defines fields (state) and methods\n(behavior). An **object** is a concrete **instance** of that blueprint,\ncreated with `new`, living on the heap with its own copy of the instance\nfields.\n\n```java\nclass Car { String color; }       \u002F\u002F blueprint\nCar a = new Car();                \u002F\u002F object 1\nCar b = new Car();                \u002F\u002F object 2 — separate state\na.color = \"red\";                  \u002F\u002F doesn't affect b\n```\n\nOne class, many objects. **Rule of thumb:** the class is the type; the\nobject is a value of that type sitting in memory.\n",{"id":28,"difficulty":14,"q":29,"a":30},"encapsulation","What is encapsulation and why does it matter?","Encapsulation means keeping fields **private** and exposing controlled access\nthrough methods, so an object protects its own invariants and you can change the\ninternals without breaking callers.\n\n```java\nclass Account {\n  private double balance;           \u002F\u002F hidden state\n  public void deposit(double amt) {\n    if (amt \u003C= 0) throw new IllegalArgumentException();\n    balance += amt;                 \u002F\u002F validated mutation\n  }\n  public double getBalance() { return balance; }\n}\n```\n\nBenefits: validation in one place, freedom to refactor representation, easier\ndebugging (state changes go through known methods), and thread-safety hooks. A\npublic mutable field gives up all of these.\n",{"id":32,"difficulty":14,"q":33,"a":34},"constructor","What is a constructor and what are its rules?","A constructor initializes a new object. It has the **class's name**, **no\nreturn type**, and runs when you use `new`. If you write none, the compiler\nsupplies a **default no-arg** constructor.\n\n```java\nclass User {\n  String name;\n  User() { this(\"anon\"); }      \u002F\u002F no-arg, chains\n  User(String name) { this.name = name; } \u002F\u002F parameterized\n}\n```\n\nRules interviewers probe: defining *any* constructor removes the free default\none; constructors can be overloaded; they're **not inherited** (but a subclass\nmust call one via `super`); and `private` constructors enable singletons and\nfactory-only construction.\n",{"id":36,"difficulty":14,"q":37,"a":38},"constructor-vs-method","How does a constructor differ from a regular method?","- A constructor has the **same name as the class** and **no return type** (not\n  even `void`); a method has any name and a declared return type.\n- A constructor runs **once**, automatically, during `new`; a method runs when\n  you call it, as often as you like.\n- Constructors are **not inherited** and can't be `final`\u002F`static`\u002F`abstract`;\n  methods can be.\n\n```java\nclass Box {\n  int size;\n  Box(int size) { this.size = size; }   \u002F\u002F constructor\n  int size() { return size; }           \u002F\u002F method (named like a getter)\n}\n```\n\nA method *named* like the class but with a return type is just a method, not a\nconstructor — a classic trick. **Rule of thumb:** no return type + class name =\nconstructor.\n",{"id":40,"difficulty":14,"q":41,"a":42},"this-keyword","What does the this keyword refer to in Java?","`this` is a reference to the **current object**. Uses: disambiguate a field\nfrom a same-named parameter, call another constructor in the same class\n(`this(...)`, constructor chaining), and pass the current instance to other\nmethods.\n\n```java\nclass Point {\n  int x, y;\n  Point(int x, int y) {\n    this.x = x;          \u002F\u002F field vs parameter\n    this.y = y;\n  }\n  Point() { this(0, 0); } \u002F\u002F chain to the other constructor\n}\n```\n\n`this(...)` for constructor chaining, like `super(...)`, must be the first\nstatement — so you can't use both in one constructor.\n",{"id":44,"difficulty":45,"q":46,"a":47},"constructor-chaining","medium","What is the order of execution when an object is constructed?","Construction runs **top-down** through the hierarchy:\n\n1. Static fields\u002Fblocks run **once** when the class first loads.\n2. On `new`: the superclass constructor runs first (via `super`), all the way\n   up to `Object`.\n3. Then instance field initializers and instance initializer blocks run.\n4. Then the rest of the subclass constructor body.\n\n```java\nclass A { A() { System.out.println(\"A ctor\"); } }\nclass B extends A {\n  int x = init();\n  int init() { System.out.println(\"B field\"); return 1; }\n  B() { System.out.println(\"B ctor\"); }\n}\n\u002F\u002F new B() prints: A ctor -> B field -> B ctor\n```\n\nA famous trap: calling an **overridable method from a constructor** runs the\nsubclass override *before* the subclass's fields are initialized — so it may see\n`null`\u002F`0`.\n",{"id":49,"difficulty":45,"q":50,"a":51},"this-vs-super-ctor","Can a constructor call both this() and super()?","No. Both `this(...)` (chain to another constructor in the same class) and\n`super(...)` (chain to the parent) must be the **first statement** in a\nconstructor — and there can only be one first statement, so you use **at most\none** of them.\n\n```java\nclass Base { Base(int n) { } }\nclass Sub extends Base {\n  Sub() { this(5); }          \u002F\u002F delegates within Sub...\n  Sub(int n) { super(n); }    \u002F\u002F ...which then reaches super\n}\n```\n\nThe pattern is to funnel overloaded constructors through `this(...)` down to one\n\"primary\" constructor that finally calls `super(...)`.\n",{"id":53,"difficulty":45,"q":54,"a":55},"initializer-blocks","What are instance and static initializer blocks?","- A **static initializer block** (`static { ... }`) runs **once** when the class\n  is loaded — used to set up `static` state that needs more than one line.\n- An **instance initializer block** (`{ ... }`) runs **on every `new`**, after\n  `super()` and before the constructor body — shared setup across overloaded\n  constructors.\n\n```java\nclass Config {\n  static final Map\u003CString,String> DEFAULTS;\n  static { DEFAULTS = new HashMap\u003C>(); DEFAULTS.put(\"env\", \"dev\"); }\n  final long created;\n  { created = System.currentTimeMillis(); }   \u002F\u002F runs for each instance\n}\n```\n\n**Rule of thumb:** prefer field initializers or constructors; reach for blocks\nonly when initialization needs logic (a loop, a try\u002Fcatch) that a single\nexpression can't express.\n",{"id":57,"difficulty":45,"q":58,"a":59},"static-keyword","What does static mean for methods, fields and nested classes?","`static` binds a member to the **class** rather than an instance:\n\n- **static field** — one shared copy across all instances.\n- **static method** — called on the class, has **no `this`**, can't access\n  instance members directly (utility methods, factories).\n- **static nested class** — doesn't hold a reference to an outer instance.\n- **static block** — runs once at class load for static setup.\n\n```java\nclass MathUtil {\n  static final double PI = 3.14159;\n  static int square(int n) { return n * n; } \u002F\u002F MathUtil.square(5)\n}\n```\n\nBecause static methods aren't tied to an object, they **can't be overridden**\n(only *hidden*) and don't participate in runtime polymorphism.\n",{"id":61,"difficulty":14,"q":62,"a":63},"instance-vs-static-members","What is the difference between instance and static members?","- An **instance member** belongs to each object — every `new` gets its own copy,\n  accessed through a reference.\n- A **static member** belongs to the class — one copy shared by all instances,\n  accessed through the class name.\n\n```java\nclass Counter {\n  static int total;     \u002F\u002F shared across all Counters\n  int id;               \u002F\u002F unique per Counter\n  Counter() { id = ++total; }\n}\nnew Counter(); new Counter();\nCounter.total;          \u002F\u002F 2 — shared\n```\n\n**Rule of thumb:** if a value or behavior is conceptually about *the type* (a\nconstant, a factory, a running count), make it `static`; if it's about *one\nobject's* state, keep it an instance member.\n",{"id":65,"difficulty":45,"q":66,"a":67},"final-class-method","What does final mean for classes, methods and fields?","- **`final` class** — cannot be extended (e.g. `String`, `Integer`). Locks the\n  design and lets the JIT optimize.\n- **`final` method** — cannot be overridden by subclasses; preserves critical\n  behavior.\n- **`final` field** — assign-once; must be set by the end of construction.\n\n```java\nfinal class Constants { }          \u002F\u002F no subclassing\nclass Base {\n  final void critical() { }        \u002F\u002F subclasses can't override\n  final int id;\n  Base(int id) { this.id = id; }   \u002F\u002F final field set in ctor\n}\n```\n\nCommon reasons: immutability (a class meant to be immutable is often `final`),\nsecurity\u002Finvariant protection, and clarity of intent. Note `final` on a\nreference fixes the *reference*, not the object it points to.\n",{"id":69,"difficulty":14,"q":70,"a":71},"access-modifiers","What are the four access modifiers in Java?","From most to least restrictive:\n\n- `private` — same class only.\n- *(default \u002F package-private)* — same package only (no keyword).\n- `protected` — same package **plus** subclasses (even in other packages).\n- `public` — everywhere.\n\n```java\npublic class Api {\n  private int secret;       \u002F\u002F class only\n  int packageScoped;        \u002F\u002F package\n  protected int forSubs;    \u002F\u002F package + subclasses\n  public int open;          \u002F\u002F everyone\n}\n```\n\nDefault the most restrictive that works (usually `private` fields) — it\nminimizes coupling. Note `protected` also grants package access, which surprises\npeople who think it's \"subclasses only.\"\n",{"id":73,"difficulty":14,"q":74,"a":75},"getter-setter","Why use getters and setters instead of public fields?","Getters\u002Fsetters keep fields **private** while exposing access through methods,\nso you can add **validation**, change the internal representation, make a field\nread-only, or add logging\u002Flazy-loading **without changing callers**.\n\n```java\nclass Temperature {\n  private double celsius;\n  public double getFahrenheit() { return celsius * 9 \u002F 5 + 32; } \u002F\u002F derived\n  public void setCelsius(double c) {\n    if (c \u003C -273.15) throw new IllegalArgumentException();        \u002F\u002F validated\n    this.celsius = c;\n  }\n}\n```\n\nA `public` field locks the API to a raw value forever. **Rule of thumb:** expose\nbehavior, not data — but don't add a getter\u002Fsetter for *every* field reflexively;\nonly where encapsulation buys something (records are better for pure data).\n",{"id":77,"difficulty":78,"q":79,"a":80},"nested-classes","hard","What are the types of nested classes in Java?","- **Static nested class** — declared `static`; no link to an outer instance, a\n  namespaced helper.\n- **Inner (non-static) class** — holds an implicit reference to its enclosing\n  instance; can access its outer fields.\n- **Local class** — declared inside a method.\n- **Anonymous class** — an unnamed inner class created and instantiated at once.\n\n```java\nclass Outer {\n  static class Helper { }            \u002F\u002F static nested\n  class Inner { }                    \u002F\u002F inner — needs an Outer instance\n  Runnable r = new Runnable() {      \u002F\u002F anonymous\n    public void run() { }\n  };\n}\n```\n\nGotcha: a non-static inner class keeps the outer object alive (potential memory\nleak), so prefer `static` nested classes unless you actually need the enclosing\ninstance.\n",{"id":82,"difficulty":45,"q":83,"a":84},"object-creation","What are the ways to create an object in Java?","- **`new`** — the normal path, invokes a constructor.\n- **Factory method** — e.g. `List.of()`, `Integer.valueOf()`, your own\n  `Builder.build()`.\n- **`Class.getDeclaredConstructor().newInstance()`** — reflection.\n- **`clone()`** — copy an existing object.\n- **Deserialization** — reconstruct from bytes (bypasses constructors).\n\n```java\nUser a = new User();                          \u002F\u002F new\nList\u003CInteger> b = List.of(1, 2);              \u002F\u002F factory\nUser c = User.class.getDeclaredConstructor().newInstance(); \u002F\u002F reflection\n```\n\nNote that reflection and deserialization can create objects **without running a\nconstructor**, which is why immutability\u002Fsingletons sometimes need extra guards.\n",{"id":86,"difficulty":45,"q":87,"a":88},"private-constructor","When would you make a constructor private?","A `private` constructor blocks outside `new`, which enables several patterns:\n\n- **Singleton** — one shared instance handed out by a static accessor.\n- **Static factory only** — force creation through named methods (`of`,\n  `valueOf`) that can cache or pick a subtype.\n- **Utility class** — a class of only `static` members that should never be\n  instantiated.\n\n```java\nfinal class MathUtil {\n  private MathUtil() { }                 \u002F\u002F no instances\n  static int square(int n) { return n * n; }\n}\nenum Config { INSTANCE; }                \u002F\u002F the preferred singleton\n```\n\n**Rule of thumb:** if a class shouldn't be instantiated freely (utility,\nsingleton, factory-controlled), hide the constructor — but for singletons an\n`enum` is the safest implementation.\n",{"id":90,"difficulty":78,"q":91,"a":92},"immutable-class","How do you design an immutable class?","Make the state impossible to change after construction:\n\n1. Mark the class `final` (no subclass can add mutability).\n2. Make all fields `private final`.\n3. Set everything in the constructor; provide **no setters**.\n4. **Defensively copy** mutable fields in and out (don't leak internal refs).\n\n```java\nfinal class Range {\n  private final int[] bounds;\n  Range(int[] bounds) { this.bounds = bounds.clone(); } \u002F\u002F copy in\n  int[] bounds() { return bounds.clone(); }             \u002F\u002F copy out\n}\n```\n\nImmutables are inherently **thread-safe**, cacheable, and safe as map keys —\n`String`, `Integer`, and `LocalDate` are all built this way. (A `record` gives\nyou most of this for free.)\n",17,null,{"description":11},"Java classes and objects interview questions — constructors and chaining, this vs super, static vs instance members, final, access modifiers, initializer blocks, nested classes, immutability and the ways to create an object.","java\u002Foop\u002Fclasses-objects","Classes & Objects","Object-Oriented Programming","oop","2026-06-19","2pfVZGzp6e4jnHO-oLqGtkNngzqwiKj2njOAk0RZJaY",[104,105,108,112,116],{"subtopic":98,"path":21,"order":20},{"subtopic":106,"path":107,"order":12},"Inheritance","\u002Fjava\u002Foop\u002Finheritance",{"subtopic":109,"path":110,"order":111},"Polymorphism","\u002Fjava\u002Foop\u002Fpolymorphism",3,{"subtopic":113,"path":114,"order":115},"Interfaces vs Abstract Classes","\u002Fjava\u002Foop\u002Finterfaces-vs-abstract",4,{"subtopic":117,"path":118,"order":119},"equals & hashCode","\u002Fjava\u002Foop\u002Fequals-hashcode",5,{"path":121,"title":122},"\u002Fblog\u002Fjava-classes-objects-constructors","Java Classes, Objects & Constructors — A Complete Guide",1782244115313]