The labs on this site need JavaScript to run. The same content is written out below.
Fundamentals › Java
Inheritance
What does extends pass down?
Why it exists — If you make similar classes separately, you have to copy the same code into every class, and when you fix it, you have to fix every class. With inheritance you write the common code once in a parent class, and a child class gets it with extends, so a child class only adds its own code or rewrites only the methods that differ. Java makes every class inherit from Object, so you can call basic methods such as toString and equals on any object.
Where it's used today — The inheritance that developers do most often is rewriting toString or equals, which they inherited from Object, with @Override, and making an exception class that fits the program with extends RuntimeException. When you write a servlet yourself, you extend HttpServlet, which a servlet container such as Tomcat provides, and rewrite methods such as doGet. If you change a parent, every child is affected, so when you only want to borrow the features of another class, you sometimes keep that object in a field and call its methods instead of inheriting.
Inheritance is the syntax where you write extends and another class name after a class name, so that the class inherits the methods and fields written in that class (the parent class). The first inheritance you meet is invisible. A class that does not write extends still has the Object class, which Java provides, as its parent, so you can call methods such as toString() even though you did not write them. If you write an inherited method again with the same name and the same parameters, the one you wrote again runs on objects of that class. This is overriding, and @Override is a mark that asks the compiler to check it. The second most common inheritance is making an exception class with extends RuntimeException. In this lab, with the example class Member and the example class MemberNotFoundException that we made, you rewrite toString(), or delete extends and change the type of a variable and of the catch, and you compile and run the same code to see what the compiler reports and what is printed.
Checked against real execution · Twenty combinations of the code on the screen (12 for Object and toString, 8 for the exception class made with extends RuntimeException) were compiled with javax.tools and run with java on JDK 21 and checked against the model, and the inheritance relations of Object, RuntimeException, and Throwable and the classes in which the methods are written were checked by reflection
Concepts in this lab
- Inheritance
- This means defining a new class (the subclass) that receives the fields and methods of an existing class (the superclass). It reuses common code, and the subclass adds or overrides only the parts it needs. A Java class supports single inheritance only, and a change to the superclass affects every subclass, so it is best used only when there is a clear "is-a" relationship.
- extends
- Where it's used today — When you make your own exception class, write an exception class that Java provides after the new class name, as in extends RuntimeException, to inherit from it, and when you make a servlet, write extends HttpServlet. When a class follows an interface, use implements, not extends.
- extends is the keyword in a class declaration that says which class the class inherits from. You write it after the class name, as in class MemberNotFoundException extends RuntimeException. The class written after it (RuntimeException, which Java provides) is the superclass, and the class being declared (MemberNotFoundException, a name chosen for this example) is the subclass. A class can write only one class after extends, and a class marked final, such as String, cannot be inherited from with extends. When you use extends, the superclass becomes a supertype of the subclass, so a variable of the superclass type can point to an object of the subclass. A class that does not use extends has Object as its superclass.
- Object class
- Why it exists — The features that every object should have in common (turning itself into text, comparing for equality, a hash code, and finding out its own class) are put in one top superclass so that each class does not have to write them separately.
- Where it's used today — The methods used to print an object as text (println, logs) and to compare elements in a collection (equals, hashCode) all come from Object. Developers write these methods again in their own classes when they need to.
- Object is a class that Java provides in the java.lang package, and it is the top superclass of every class. If a class declaration does not write extends, the superclass of that class is Object, and even if it inherits another class with extends, going up the chain you reach Object. So on any object you can call methods written in Object, such as toString(), equals(Object), hashCode(), and getClass(), and a variable of type Object can point to an object of any class.
- toString()
- Where it's used today — A DTO or entity class overrides toString() so that an object shows up in a readable way in logs, in the debugger, and in error messages. Java's record makes toString() for you automatically.
- toString() is a method that returns a String that shows an object as text. It is written in Object, so every object inherits it. The body written in Object is getClass().getName() + "@" + Integer.toHexString(hashCode()), so if you do not write it again, you get text that joins the class name, @, and the hash code written in hexadecimal, as in Member@279f2327. System.out.println(object) and string + object use the text they get by calling toString() of that object. If a class adds @Override and writes public String toString() again, you can change that text.
- Overriding
- Why it exists — When an inherited method does not fit a subclass, creating a new method with a different name means that code calling through the supertype still runs the old inherited behavior. Overriding redefines the method with the same signature so that the new behavior runs even when it is called through the supertype.
- Where it's used today — It is used when you rewrite toString, equals, and hashCode to suit a class, and when you implement the methods of an interface. If you add @Override, the compiler catches the mistake of writing the name or parameters wrongly and ending up with a new method.
- This means that a subclass redefines a method of its superclass (or of an interface) with the same signature. At run time, the method that matches the type of the actual object is called, and this is how polymorphism is implemented. The access level cannot be made narrower, and static, private, and final methods cannot be overridden.
- @Override
- Why it exists — Overriding happens quietly as long as the name and parameters match, so if the name of the parent's method is changed later, the child's method stays as a separate method that is not an override, with no error at all. @Override writes the intention to override in the code, so that such a mismatch shows up as a compile-time error.
- Where it's used today — You put it when you override toString, equals, or hashCode, or when you implement a method of an interface. When an IDE generates overriding code for you, it writes it too.
- This is an annotation that shows that the method right below it overrides a method of a superclass or an interface. The compiler reads this tag and checks that it really overrides, and if not, it reports a compile-time error. It catches the mistake of misspelling the method name or its parameters and so creating a new method that does not override. It overrides even without it, and the behavior of the program does not change either, but to prevent mistakes you always put it on a method that overrides. It is an annotation that is kept only up to the source code, so it is not written to the class file.
- RuntimeException
- Where it's used today — It is the parent used most often when you make an exception class that fits your program, as in class MemberNotFoundException extends RuntimeException. You write a constructor and pass the message with super(message), and since constructors are not inherited, you have to write it yourself. Spring also made its data access exception (DataAccessException) a class that inherits RuntimeException.
- RuntimeException is an exception class that Java provides in the java.lang package. It inherits Exception, and Exception inherits Throwable. RuntimeException and its subclasses are exceptions (unchecked exceptions) for which the compiler does not require you to write throws on the method declaration or to catch them with catch. NullPointerException, IllegalArgumentException, and ArithmeticException are all children of RuntimeException. An exception made with the constructor RuntimeException(String message) returns that message from getMessage(). getMessage() is written in Throwable.
- Superclass and subclass
- A superclass is a class that other classes inherit from with extends, and a subclass is a class that names its superclass with extends. In class MemberNotFoundException extends RuntimeException, RuntimeException is the superclass. A subclass inherits those methods of its superclass that it can access, so you can call them on an object of the subclass even if the subclass does not write them. Constructors are not inherited. If the subclass writes a method again with the same name and the same parameters, that one runs on objects of the subclass, and this is overriding. Every class further up the chain, such as the superclass of a superclass, is also called a superclass. RuntimeException inherits Exception, Exception inherits Throwable, and Throwable inherits Object.
Try these
- Default settings — Member inherits Java's Object even though it does not write extends. The toString() written in Object runs, and the class name and the hash code are printed, as in Member@279f2327.
- Write toString() again — The toString() that you wrote again in Member runs, and Member(Alice) is printed. println also calls that toString().
- Point to it with a variable of type Object — Member is a child of Object, so a variable of type Object can point to it. The toString() that runs is still the one written again in Member.
- Point to it with a variable of type String — Member does not inherit from String, so it is not of type String. There is a compile-time error.
- Misspell the name and add @Override — tostring is a method that the parent does not have, so it is not overriding. Because of @Override, the compiler reports it as an error.
- Misspell the name without @Override — It compiles, but tostring is just a new method, so the output is Member@279f2327, exactly what the toString() of Object makes.
- Make an exception class — It inherits RuntimeException and becomes an exception object, so you can use it with throw and catch, and you can also call getMessage(), which you did not write.
- Receive it with the type RuntimeException — MemberNotFoundException is a child of RuntimeException, so the variable e of the parent type receives that object.
- Delete extends RuntimeException — It becomes an ordinary class whose parent is Object, and there are compile-time errors at super(message), throw, catch, and getMessage().
- Do not write the constructor — Constructors are not inherited. There is no constructor that takes a message, so there is a compile-time error.
Running with the default settings
- The compiler reads the line class Member {. Member is a class made as an example in this lab, and there is no extends after the class name. The Java specification says that a class that does not write extends has the Object class, which Java provides, as its parent. So Member inherits methods written in Object, such as toString(), equals(), hashCode(), and getClass(). What is written directly inside Member is the field name and the constructor.
- toString() is not written in Member. Then the toString() you call on a Member object is the one written in Object. The body that Java wrote there is the single line return getClass().getName() + "@" + Integer.toHexString(hashCode());, which joins the class name, @, and the hash code of that object written in hexadecimal, and returns the result.
- The compiler checks the line Member m = new Member("Alice");. The new Member("Alice") on the right is an expression that creates a Member object, and the variable m on the left is of type Member. The types are the same, so it passes.
- The compiler checks the lines m.toString() and System.out.println(m). toString() is a method inherited from Object, so you can call it, and println takes any object. These two lines are not errors.
- Compilation succeeds and the Main class file is made.
- java Main runs it. new Member("Alice") creates a Member object, and the variable m points to that object.
- m.toString() runs. The toString() to run is looked up first in the class of the object that m points to, Member. Member has no toString(), so the toString() written in the parent Object runs and returns Member@279f2327, and that text is printed. Member at the front is the class name, and 279f2327 after @ is the hash code of this object written in hexadecimal. This value came out when it was run in the environment of this lab. Java does not say that the hash code is the same on every run, so a different value may come out.
- The line System.out.println(m) runs. println is a method that Java provides, and when it receives an object, it goes through String.valueOf, calls toString() of that object, and prints the text it gets back. So the same text as the previous line, which wrote m.toString() (Member@279f2327), is printed once more. What is printed when you print an object with println is decided by the toString() of its class.
Result of this run
- Member did not write extends, but it inherits Java's Object, so it could call toString(), which Member did not write. What ran is the toString() written in Object, and Member@279f2327, which joins the class name and the hash code, was printed.
- Every class in Java inherits Object like this. You were already using inheritance before you wrote extends yourself. println(m) also called that toString() and printed the same text.
Code
// Member is a class made as an example in this lab (it does not write extends)
class Member {
String name;
Member(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
// The type of the variable m is Member, and what is created on the right is a Member object
Member m = new Member("Alice");
// Calls, through m, the toString() that Member did not write
System.out.println(m.toString());
// println calls toString() of the object it receives and prints the result
System.out.println(m);
}
}
Assumptions of this model
The compiler and runtime are JDK 21.0.12.1 (javac 21). For all twenty combinations (12 for the Object scene and 8 for the exception scene), the same text as the code on the screen (the source that the code function makes, written to a file exactly as it is) was compiled with javax.tools, and the ones that compiled successfully were run separately with java -cp, and the results were checked against the standard output, standard error, and exit code that were captured. What was checked is whether compilation succeeded, the diagnostic code and the English message of the first error (the error descriptions on the screen restate these in plain words), the number of errors and the lines where they occurred, whether the Main class file was made, and the output when run. The number of errors and the line where each occurs are not fixed by the specification but were observed on this javac. For example, when the constructor was not written, even without extends, the error on the throw line came out as just the one constructor error. The facts that the step sentences rely on were also checked by reflection: that the parent of Member, which does not write extends, is java.lang.Object, and that toString, equals, hashCode, and getClass are written in Object; that if you write toString again it becomes the one in Member, and if you mistakenly write it as tostring, toString is still the one in Object; that MemberNotFoundException links to RuntimeException, Exception, Throwable, and Object, and getMessage is written in Throwable; that RuntimeException has a RuntimeException(String) constructor; and that an exception class that writes no constructor gets just one no-argument constructor. The 279f2327 in Member@279f2327 is a value that came out the same all four times that the same program was run in this environment. The description of Object.hashCode in Java says that this value does not have to be the same on every run, so a different value may come out in another environment. The behavior of the Java API was checked by opening the source that comes with this JDK (lib/src.zip). It was confirmed that the body of Object.toString is getClass().getName() + "@" + Integer.toHexString(hashCode()), that PrintStream.println(Object) gets the text with String.valueOf and String.valueOf calls toString() if the object is not null, and that RuntimeException(String message) saves the message it received so that getMessage() can take it out again. The specification was checked by opening the Java Language Specification (Java SE 21) directly. That the extends clause decides the direct superclass, and that the direct superclass of an ordinary class that does not write extends is Object, is from Section 8.1.4; that a class inherits the methods of its direct superclass is from Sections 8.2 and 8.4.8; that constructors are not members and so are not inherited is from Sections 8.2 and 8.8; that if you write no constructor at all, a default constructor with no arguments is made is from Section 8.8.9; that it is a compile-time error if a method with @Override does not override a method of its superclass is from Section 9.6.4.4; that the expression of throw must have a type that can be assigned to Throwable is from Section 14.18; that the type written in catch must be Throwable or a subclass of it is from Section 14.20; that if the actual class of the thrown object can be assigned to the type of catch, that catch is chosen is from Section 14.20.1; that a value of a child type can be assigned to a variable of the parent type is from Sections 5.1.5 and 5.2; and that at run time a method is looked up from the actual class of the object upward is from Section 15.12.4.4. The code on the screen has all the classes in one file, and the access modifiers are cut down. For the super(message) of the constructor used when making an exception class, only passing the message was covered, and the order in which the parent constructor runs and the detailed rules of super are covered in the "In-depth lab: Inheritance and overriding". The rule of overriding equals and hashCode together, the inheritance of fields, the fact that private members are not inherited, checked exceptions made with extends Exception, and extends HttpServlet for a servlet were not run in this lab. A servlet that inherits HttpServlet is actually deployed on Tomcat in the "Servlets" lab (Fundamentals).
Previous lab: static · Next lab: Interfaces