Skip to lesson

Parent delegation

When a class loader is asked for a class, it does not search its own place first. It asks its parent first, all the way up to the bootstrap loader, and searches itself only if no parent can find the class.

A loader asks its parent first before loading a class itself

Parent delegation is the rule that a class loader first asks its parent to load a class and loads it itself only if the parent cannot.

Parent delegation is the rule every built-in loader follows when loadClass(name) is called: hand the request to the parent first, and look for the class yourself only if the parent fails.

  1. Check whether this loader has already loaded the class. If yes, return the same Class object.
  2. Ask the parent loader to load it. The parent repeats these steps with its own parent.
  3. At the top, the bootstrap loader looks among the core classes.
  4. If no parent found the class, call this loader's own findClass(name).
  5. If findClass fails too, throw ClassNotFoundException back to whoever asked (often the child, which then tries its own findClass).
Three class loaders in a chain. The request to load Shop goes up from the application loader to the platform loader and then to the bootstrap loader, and each one asks its parent first. If the parent cannot find the class, the request comes back down and the next loader tries itself.

Example 1 · Logging every step of delegation

DelegationDemo.javaJava
class LoggingLoader extends ClassLoader {    LoggingLoader(String name, ClassLoader parent) {        super(name, parent);    }
    @Override    protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {        System.out.println(getName() + ": loadClass(" + className + ")");        return super.loadClass(className, resolve);   // the normal delegation    }
    @Override    protected Class<?> findClass(String className) throws ClassNotFoundException {        System.out.println(getName() + ": findClass(" + className + ") - not found here");        throw new ClassNotFoundException(className);    }}
class Marksheet {}
public class DelegationDemo {    static String loaderName(Class<?> c) {        ClassLoader l = c.getClassLoader();        return l == null ? "bootstrap" : l.getName();    }
    public static void main(String[] args) {        ClassLoader app = DelegationDemo.class.getClassLoader();        LoggingLoader college = new LoggingLoader("college", app);        LoggingLoader dept = new LoggingLoader("dept", college);
        String[] names = {"java.lang.String", "Marksheet", "Hallticket"};        for (String n : names) {            System.out.println("Asking dept for " + n);            try {                Class<?> c = dept.loadClass(n);                System.out.println("  -> loaded by " + loaderName(c));            } catch (ClassNotFoundException e) {                System.out.println("  -> ClassNotFoundException: " + e.getMessage());            }        }    }}
Output
Asking dept for java.lang.String
dept: loadClass(java.lang.String)
college: loadClass(java.lang.String)
  -> loaded by bootstrap
Asking dept for Marksheet
dept: loadClass(Marksheet)
college: loadClass(Marksheet)
  -> loaded by app
Asking dept for Hallticket
dept: loadClass(Hallticket)
college: loadClass(Hallticket)
college: findClass(Hallticket) - not found here
dept: findClass(Hallticket) - not found here
  -> ClassNotFoundException: Hallticket

What this code does

  • The chain is dept → college → app → platform → bootstrap. Each request climbs it: String is found at the top by bootstrap, Marksheet by app, and neither custom loader's findClass runs.
  • Hallticket exists nowhere. Every parent fails, so the findClass calls run on the way back down: college first, then dept, and finally ClassNotFoundException reaches main.

The parent does the same with its own parent, so a request climbs the chain up to the bootstrap loader.

So the search order is top-down: bootstrap first, then platform, then app, then your custom loader.

Why delegation keeps core classes safe and unique

Because every request reaches the bootstrap loader first, a core class such as java.lang.String is always the one from the JDK. A String class sitting on your class path is never even looked at.

Example 2 · Trying to replace java.lang.String

Terminal
# java/lang/String.java contains: package java.lang; public class String { main(...) }javac java/lang/String.java# compile it in the old Java 8 mode, then try to run itjavac --release 8 -d out java/lang/String.javajava -cp out java.lang.String
Sample output
java\lang\String.java:1: error: package exists in another module: java.base
package java.lang;
^
1 error
...
Error: Main method not found in class java.lang.String, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

What this code does

  • A real run with JDK 21 on Windows, trimmed (the --release 8 step prints only warnings about the old release). On Java 9 and later, javac itself refuses: the package java.lang belongs to the java.base module.
  • Even with the class compiled, java asks the application loader, which delegates up to bootstrap. Bootstrap finds the real String, which has no main. The fake out/java/lang/String.class is never loaded.

Example 3 · A custom loader cannot define a java.* class

ProtectedPackageDemo.javaJava
class RogueLoader extends ClassLoader {    RogueLoader() {        super("rogue", ClassLoader.getSystemClassLoader());    }
    Class<?> tryToDefine(String name, byte[] bytes) {        return defineClass(name, bytes, 0, bytes.length);    }}
public class ProtectedPackageDemo {    public static void main(String[] args) throws Exception {        RogueLoader rogue = new RogueLoader();
        Class<?> s = rogue.loadClass("java.lang.String");        System.out.println("Asked rogue for java.lang.String, defining loader: " + s.getClassLoader());        System.out.println("Same String class as everyone else: " + (s == String.class));
        try {            rogue.tryToDefine("java.lang.FakeString", new byte[0]);        } catch (SecurityException e) {            System.out.println("SecurityException: " + e.getMessage());        }    }}
Output
Asked rogue for java.lang.String, defining loader: null
Same String class as everyone else: true
SecurityException: Prohibited package name: java.lang

What this code does

  • Asking rogue for String goes up the chain and returns the bootstrap's String, the same Class object every other class uses.
  • defineClass checks the name before it even reads the bytes: any java.* name from a non-platform loader is refused with SecurityException.

This gives two guarantees. Safety: no library or downloaded code can swap in its own String, Object or SecurityManager. Uniqueness: there is exactly one String class in the JVM, so a String from one library can be passed to any other library. A second wall protects the core packages: ClassLoader.defineClass refuses any class name in a java.* package unless it is the platform loader, and on Java 9 and later javac refuses to compile a class into a package that the JDK's modules already own.

loadClass versus findClass

loadClass(name) is the public entry point: it checks the cache, delegates to the parent and, only if that fails, calls findClass(name). findClass is the protected method that looks in this loader's own place: a folder, a JAR, a database or the network.

Example 4 · findClass runs only when the parents fail

FindClassDemo.javaJava
import java.io.IOException;import java.io.InputStream;
class Notice {    public String toString() {        return "Exam timetable is out";    }}
class FolderLoader extends ClassLoader {    FolderLoader(String name, ClassLoader parent) {        super(name, parent);    }
    @Override    protected Class<?> findClass(String className) throws ClassNotFoundException {        System.out.println("  " + getName() + ".findClass(" + className + ")");        String file = className.replace('.', '/') + ".class";        // For this demo the bytes come from the class path; a real loader        // would read them from its own folder, JAR, database or network.        try (InputStream in = ClassLoader.getSystemResourceAsStream(file)) {            if (in == null) {                throw new ClassNotFoundException(className);            }            byte[] bytes = in.readAllBytes();            return defineClass(className, bytes, 0, bytes.length);        } catch (IOException e) {            throw new ClassNotFoundException(className, e);        }    }}
public class FindClassDemo {    public static void main(String[] args) throws Exception {        // parent = platform, so the parent cannot see the class path        FolderLoader loader = new FolderLoader("notices", ClassLoader.getPlatformClassLoader());
        System.out.println("loadClass(java.lang.String):");        Class<?> s = loader.loadClass("java.lang.String");        System.out.println("  defined by: " + (s.getClassLoader() == null ? "bootstrap" : s.getClassLoader().getName()));
        System.out.println("loadClass(Notice):");        Class<?> n = loader.loadClass("Notice");        System.out.println("  defined by: " + n.getClassLoader().getName());
        System.out.println("loadClass(Notice) again:");        Class<?> again = loader.loadClass("Notice");        System.out.println("  same Class object: " + (again == n));        System.out.println("Same as the app's Notice.class: " + (n == Notice.class));    }}
Output
loadClass(java.lang.String):
  defined by: bootstrap
loadClass(Notice):
  notices.findClass(Notice)
  defined by: notices
loadClass(Notice) again:
  same Class object: true
Same as the app's Notice.class: false

What this code does

  • FolderLoader overrides only findClass. For String the parent chain succeeds, so findClass is never called. For Notice the platform parent fails, so findClass reads the bytes and calls defineClass.
  • The second request is answered from the loader's cache, with no findClass call. And the Notice defined by notices is a different class from the app's Notice: same name, different loader.

To write a custom loader, override findClass and leave loadClass alone. You keep delegation for free, and you only write the part that is really yours: get the bytes, then call defineClass(name, bytes, 0, length) to turn them into a Class. Overriding loadClass changes the delegation order itself. Some servers do this on purpose ("child-first" loading, described in the interview tab), but most code should not.

What happens when the same class is on the class path twice

The application loader searches the class path in order, entry by entry, and takes the first match. If FeeRules.class is in both v1 and v2, the one in the entry listed first wins, and the other copy is silently ignored.

Example 5 · The same class in two folders: the first one wins

Terminal
# v1/FeeRules.class says "fee rules v1 (hostel Rs 40000)"# v2/FeeRules.class says "fee rules v2 (hostel Rs 45000)"java -cp "app;v1;v2" FeeAppjava -cp "app;v2;v1" FeeAppjava -Xlog:class+load -cp "app;v2;v1" FeeApp | findstr FeeRules
Sample output
Using fee rules v1 (hostel Rs 40000)
Using fee rules v2 (hostel Rs 45000)
[0.105s][info][class,load] FeeRules source: file:/C:/.../twice/v2/

What this code does

  • A real run on Windows with JDK 21 (on macOS write app:v1:v2 and use grep). The same command with the folders swapped gives a different hostel fee, and Java prints no warning at all.
  • The load log names the folder the class really came from. When two versions of a library are on the class path, this line tells you which one is running.

There is no warning and no error.

This is a classic source of "it works on my machine" bugs, sometimes called JAR hell: two versions of the same library end up on the class path, and the order decides which one runs. -Xlog:class+load shows the source of each class, so you can see which copy was used.

The class path separator is ; on Windows and : on macOS and Linux.

Next step

Check your understanding

11 quick questions