Inheritance

Inherently good for you.

For today

  • Why?
  • What?
  • How?

Why Inheritance?

class Student
    introduce()
    getName()
    getBirthday()
    getGpa()
    

class Professor
    introduce()
    getName()
    getBirthday()
    getClassName()    

INHERITANCE

What is Inheritance?

Our case

Student

Professor

?

Person

Inheritance:

Inheriting a parent class' fields and methods

With Inheritance, we can:

  • Declare new fields
  • Declare new methods
  • Override parent methods with a custom implementation

How do we use inheritance?

In Java

public class Professor extends Person {
}

keyword: extends

SUBCLASS (CHILD)

SUPERCLASS

 (PARENT)

AKA:

public class Person {
    public String name;
    public String birthday;

    public Person() { ... }
    public String getName() { ... }
    public String getBirthday() { ... }
    public String introduce() { ... }
}
public class Professor extends Person {
    public String className;
    
    public Professor() { ... }
    public String getClassName() { ... }
}
public class Student extends Person {
    public float gpa;
 
    public Student() { ... }   
    public float getGPA() { ... }
}
public static void main(String[] args) {
    ....

    Student student = new Student("Charles", "4/11/1995", 3.4);
    System.out.println(student.introduce());
}

Where is introduce()?

Student -> Person

Nope!

Yep!

public class Professor extends Person {
    public String className;
    
    public Professor() { ... }
    public String getClassName() { ... }
    public String introduce() { ... }
}

Declaring a new field

Declaring a new method

Override a parent method

In Action

super()

Next Time:

It's super() important.

Inheritance

By Charles Xue

Inheritance

  • 998