Inheritance and Polymorphisan
Inheritance
- What:
- student和faculty都是person。总结出一个person的super class
- 把属于person的共同代码写在parent class里,包括instance和method。
- 把属于student和faculty自己的代码写在subclass里,包括instance和method。
- Why:
- 维护代码方便
- 把不同的class放在同一个data structure里,方便操作
- Person[] p = new Person[3];
- p[0] = new Person();
- p[1] = new Student();
- p[2] = new Faculty();
- Note:
- Person p = new Student()--is allowed because student is a person. But compiler will see p as a person, only during runtime, p will be regarded as student.
Polymorphism
- What:
- Superclass reference to subclass object: Person s = new Student(“Cara”, 1)
- Subclass can call their own version of methods (overriding)
- Why:
- Need different version of one methods
- Notes:
- When compile: compiler only know reference type (for example: person), be caution for compile errors (for example: use methods only in student not in person, compiler only looks for person class) (sometimes need casting to subclass)
- When run: will execute the real type
Overloading vs. Overriding
- Same class has same method name with different parameters
- Subclass has same method name with same parameter
Visibility
- Public: can access from any class
- Protected: can access from same class/same package/any subclass
- Package: can access from same class/same package
- Private: can access from same class
- Rule of thumb: make member variables private, methods can be private or public (for example: method for others to access member value is normally public, while helper method does not want others to use is private)
- Protected or package rarely used
Construction
- Construction happens from subclass to parent class
- No constructor: java gives a default one with no arguments
- First line should say either this or super, otherwise, java will insert super() for you
- How to initialize parent instance in subclass? call super(arguments)
Abstract classes vs. interface (this part not clear, need rewrite)
- Abstract, define instance and methods
- public abstract class Person{
- public abstract void Monthlypaycheck (); }
- Interface, define method only
public interface Comparable
{ public abstract int compareto(); } why?
- Force subclasses to have this method
- Person class do not define actual implementation