Introduction

This notebook goes over Objects and Inheritance.

The Superclass

Also called the parent class, this is the base class that child classes inherit properties from. The superclass in this example is a Person class. It has the properties of name and age. It has two methods, which are both getters, and one template method which is a CustomNumber method.

public class Person {
    public String name;
    public int age;

    public Person (String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person () {
        this.name = "-1";
        this.age = -1;
    }

    public String GetName () {
        return this.name;
    }

    public int GetAge() {
        return this.age;
    }

    public int CustomNumber() {
        return 0;
    }
}

The child class

Now we have a student class. A student is also a person, and therefore the student "inherits" from the person class. This concept is called inheritance, and is implemented in java through the "extends" keyword. What this means is that the student class, by default, will have the same properties as the Person class and the same methods.

But the student will have some more properties than a default person. So, we can add the proerties of grade and id. We can also give the template method, CustomNumber, functionality now. We do this by using the "@Override" keyword. This means that we can essentially redefine this method to do something different. Here, we return the id with this method.

As shown, all of the methods and properties of the Person class are still present. But there's now more methods and properties!

public class Student extends Person {

    public int grade;
    public int id;

    public Student (String name, int age, int grade, int id) {
        this.name = name;
        this.age = age;
        this.grade = grade;
        this.id = id;
    }

    public Student () {
        this.name = "-1";
        this.age = -1;
        this.grade = -1;
        this.id = 0;
    }

    public int GetGrade() {
        return this.grade;
    }

    // Overriding the template method, CustomNumber
    @Override public int CustomNumber () {
        return this.id;
    }

    public static void main(String[] args) {
        // Creating an object of the Student class and assigning it properties.
        Student student1 = new Student("Sahil", 16, 12, 1234567);

        // Printing out values to show that all properties and methods are preserved from base class, and new ones are there from child class.
        System.out.println(student1.GetName());
        System.out.println(student1.GetAge());
        System.out.println(student1.GetGrade());
        System.out.println(student1.CustomNumber());

    }

}
Student.main(null);
Sahil
16
12
1234567