Subtype Substitution Principle Type Every variable in Java
Subtype Substitution Principle
Type • Every variable in Java has a type. Specifically, every reference variable has two types: static type and dynamic type. • A type in Java can be one of the following: – Primitive type: int, float, double, boolean, and char. – Any classes: • Built-in classes: Object, String, and Integer etc. • User-defined classes: Student, Person, and University etc. – Interfaces 9 -2
Subtype • Type B is a subtype of Type A if – A is an interface and B implements A, OR, – A are B both are interfaces and B extends A, OR, – A is a class and B extends A A A OR B B • As special case, any type A is a subtype of A
How Does Compiler Do? • Recall compiler tries to detect as many runtime errors as possible. • Static Type checking is one of the ways for compiler to avoid runtime errors. • Why the static type of the RHS of assignment should be a subtype of the static type of the LHS of assignment.
Subtype Type Substitution • If type B is a subtype of type A and everywhere the code expects A, then a B can be used instead. • “The code expects A” follows the “first write first dominate (FWFD)” principle. For instance: Person p = new Student(); … public Person m(Student s) { …… return new Student(); } x. m(new Collegestudent ()); producer client/consumer
- Slides: 5