To understand this topic you should know what are compilation and run-time processes in general. In short, when you build your app compiler goes through all your code and checks for consistency, safety and run-ability. If there is no error founded by compiler it generates class
files from your source code (java
files). When the app is running it means that your class
files are loaded into memory and JVM executing your app instruction by instruction.
From your example:
Person a = new Student(); // Student is a subclass of Person
a.speak();
Compilation process:
Compiler checks this line: Person a = new Student();
for type safety (compatibility). So, if student is a
person compilation goes to next line else it fails. In next line: a.speak();
compiler looks at a
type, found that it's a Person
and looks for speak()
method at Person
type. If that method is not founded by compiler compilation process fails.
Runtime process:
When JVM executes this line: Person a = new Student();
it goes through initialization process from top (parent class) to bottom (child class). In next line: a.speak();
JVM founds student
object through reference a
looks for method speak()
if it's founded in Student
then executes it, otherwise it runs speak()
method from parent class Person
.
Another examples from inheritance subject:
class Person {
public void speak() {}
public void think() {}
}
class Student extends Person {
@Override
public void speak() {}
public void speakALot() {}
}
Person a = new Student();
a.speak(); // calling overrided version of speak()
a.think(); // since this method is not overrided in child class it will be called from parent class
a.speakALot(); // since Person doesn't know anything about specific methods of derived classes compilation fails
Student b = new Student();
b.speak(); // calling speak() method of student object
b.think(); // inheritance trick, child class keeps reference to its base class and that's why public and protected fields and methods are available
b.speakALot(); // calling speakALot() method of student object