Inheritance

inheritance
Person.java
public class Person {
    private String name;
    private String gender;
    private int age;

    public Person() {
        this("Mary", "female", 10);
    }

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

    public String getName() {
        return name;
    }

    public String getGender() {
        return gender;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

The keyword extends means to inherit from a father class.

Student.java
public class Student extends Person{
    private String school;

    public Student(String school) {
        this.school = school;
    }

    public void schoolType(){
        System.out.println(super.getName() + " is in " + school);
    }
}

The keyword super means to get the father class variable or method. You could also use override to rewirte the father class method to use only in a sun class.

Main.java
public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.getName() + " is " + person.getGender());

        Student student = new Student("High School");
        student.schoolType();
    }
}

The snippet output is

Mary is female

Mary is in High School

Last updated