What is a constructor, and how is it different from a method?
A constructor runs once when an object is created and puts it into a valid starting state. It has the class's name, no return type (not even
void), and is not inherited. The trap: Java adds a no-argument default constructor only when you write none, so after addingPoint(int x, int y),new Point()stops compiling. See Java constructors.What is constructor overloading and constructor chaining?
Constructor overloading is several constructors with different parameter lists. Chaining is one constructor calling another with
this(...), or the parent's withsuper(...), so the setup lives in one place.Javapublic class Main { public static void main(String[] args) { System.out.println(new Pizza() + " " + new Pizza("large") + " " + new Pizza("small", "thick")); } } class Pizza { final String size; final String crust; Pizza() { this("medium"); } Pizza(String size) { this(size, "thin"); } Pizza(String size, String crust) { this.size = size; this.crust = crust; } @Override public String toString() { return size + "/" + crust; } }It prints
medium/thin large/thin small/thick. Before Java 25 the call must be the first statement (Java 22 to 24 only previewed the change); Java 25 allows code before it that does not read the object being built, see JEP 513.What are the types of constructors? Does Python have a constructor?
Default (no arguments), parameterized and copy (built from another object of the same class). Java and C++ add a default constructor only if you write none. C++ generates a memberwise copy constructor unless you declare your own, and deletes it if you declare a move operation; Java has none, so you write
Point(Point other). Python has one__init__, which strictly is the initializer:__new__creates the object.In what order do constructors run in a three-level Java class hierarchy?
Javapublic class Main { public static void main(String[] args) { new C(); } } class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } } class C extends B { C() { System.out.print("C"); } }Every constructor starts with an implicit
super(), soC()first callsB(), which first callsA(). The parent is built before the child adds its part. C++ destructors run the other way, child first.In what order do Java static blocks, instance blocks and constructors run?
Javapublic class Main { public static void main(String[] args) { new Box(); new Box(); } } class Box { static { System.out.print("static "); } { System.out.print("init "); } Box() { System.out.print("ctor "); } }A static initializer runs once, when the class is initialized on first use; an instance initializer runs for every object, before the constructor body. So the first
new Box()prints all three and the second onlyinit ctor.Can a constructor be private? When would you make one private?
Yes. A private constructor means only the class itself can create instances. Uses: a singleton, static factories (
LocalDate.of(2026, 1, 15)decides what to return), utility classes such asjava.lang.Math, and builders. A class whose constructors are all private cannot be subclassed outside the top-level class that contains it, since a subclass constructor must callsuper(...).What are the
thisandsuperkeywords used for?thisrefers to the current object;superrefers to the parent class's part of it.thistells a field from a parameter (this.name = name;) and calls another constructor (this(size, "thin");).supercalls the parent constructor or the parent version of an overridden method (super.info()). Neither exists in astaticmethod.What is the difference between static and instance members?
An instance member belongs to each object, which has its own copy of every instance field; a static member belongs to the class and is shared by all objects. Static members are reached through the class (
Math.max(...)), have nothis, and suit counters, constants and utility methods. More in Java static members.Which methods does every Java class inherit from
Object?Every class inherits
equals(),hashCode(),toString(),getClass(),clone(),wait(),notify(),notifyAll()andfinalize()fromjava.lang.Object. Overrideequals()andhashCode()together or hash collections break; the defaulttoString()prints something likePoint@1b6d3586;finalize()is deprecated for removal since Java 18 (JEP 421).Does Java have destructors? How is cleanup done?
No. The garbage collector frees memory when an object becomes unreachable, at a time you do not control. For files, sockets and connections, implement
AutoCloseableand usetry-with-resources, which callsclose()deterministically:Javapublic class Main { public static void main(String[] args) { try (Resource a = new Resource("db"); Resource b = new Resource("file")) { System.out.println("working"); } } } class Resource implements AutoCloseable { private final String name; Resource(String name) { this.name = name; System.out.println("open " + name); } @Override public void close() { System.out.println("close " + name); } }It prints
open db,open file,working,close file,close db: resources close in reverse order. See Java try-catch.What is the difference between a shallow copy and a deep copy?
A shallow copy copies the fields as they are, so referenced objects are shared; a deep copy also copies the referenced objects, so the two are independent.
Javaimport java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { Order original = new Order(new ArrayList<>(List.of("tea"))); Order shallow = new Order(original, false); Order deep = new Order(original, true); original.items.add("cake"); System.out.println(shallow.items + " " + deep.items); } } class Order { final List<String> items; Order(List<String> items) { this.items = items; } Order(Order other, boolean deep) { this.items = deep ? new ArrayList<>(other.items) : other.items; } }It prints
[tea, cake] [tea]: the shallow copy saw the change.Object.clone()is shallow, so prefer a copy constructor.How do you model a linked list node or a tree node as a class?
A node is a small class holding a value and references to other nodes:
nextfor a linked list,leftandrightfor a binary tree.Javapublic class Main { public static void main(String[] args) { Node head = new Node(1, new Node(2, new Node(3, null))); Node prev = null; while (head != null) { Node next = head.next; head.next = prev; prev = head; head = next; } for (Node n = prev; n != null; n = n.next) { System.out.print(n.val + " "); } System.out.println(); } } class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }It reverses
1 -> 2 -> 3by re-pointing references and prints3 2 1. Most linked list and tree problems start with this class.Practice it: Reverse Linked List, Middle of the Linked List, Maximum Depth of Binary Tree, Invert Binary Tree
Classes, Objects and Constructors Interview Questions
Constructors, initialization order, this and super, static members, copying and cleanup.