1. Single Inheritance
The extends keyword
Inheritance allows one class to include all the fields and methods from another class. For example, here we have class Student 'extending' class Person
class Person { int age; String name; } class Student extends Person { double gpa; } //now given Student student = new Student(); //both student.age and student.name are valid.
In the above example, Student extends Person, so each student has an int age and String name. We call Student the subclass and Person the superclass.
Inheriting methods
A subclass also inherits all the methods from the superclass. Unless these methods are marked 'private', the subclass can also access the superclasses methods:
class Person { int age; String name; int getAge() { return age; } } class Student extends Person { double gpa; int getGraduationYear() { return 2020 - getAge(); //runs getAge() in Person } } //now given Student student = new Student(); //and student.age = 10; //getGraduationYear() returns 2020-10
Overwriting a method in the subclass
You can re-declare a method with the same signature in the subclass. For example, here we have both Person and Student defining a "getName" method:
class Person { int age; String name = "Alice"; //defaults to Alice int getAge() { return age; } String getName() { return name; } } class Student extends Person { double gpa; int getGraduationYear() { return 2020 - getAge(); //runs getAge() in Person } String getName() { return name+" the student"; } } //Given Person person = new Person(); //and Student student = new Student(); //person.getName() returns "Alice" //student.getName() returns "Alice the student"
When you overwrite a method, the subclass method is run instead of the superclasses method. However, you can still create objects of the superclass type and run the superclass method (in this case new Person())
Constructors are chained
Instantiating an object of the subclass still runs the constructor of the superclass. Take this example:
class Person { int age; String name = "Alice"; //defaults to Alice Person() { System.out.println("You made a person!"); } int getAge() { return age; } String getName() { return name; } } class Student extends Person { double gpa; Student() { System.out.println("You made a student!"); } int getGraduationYear() { return 2020 - getAge(); //runs getAge() in Person } String getName() { return name+" the student"; } } //Even if you only run Student student = new Student(), both constructors will run.
In the above example, new Student() runs BOTH the new Person() constructor as well as the new Student() constructor. This is a subclass constructor *must* call the superclass constructor. If you do not explicitly call the superclass constructor, Java will automatically call the superclass constructor with no arguments.