继承,子类继承父类。
Why:
Good for complex, large projects.
1. Keep common behavior in one class.
2. Split different behavior in separate classes.
3. Keep all of the objects in a single data structure.
How:
Use "extends"
Details:
What is inherited?
1. Public instance variables.
2. Public methods.
3. Private instance variables (can only be accessed via public methods eg. getter and setter).
Person p = new Student(); //correct, a student is a person
// Following is fine
Person[] p = new Person[3];
p[0] = new Person();
p[1] = new Student();
p[2] = new Faculty();
public class Person { private String name; public String getName() { return name; } } public class Student extends Person { private int id; public int getId() { return id; } } public class Faculty extends Person { private String id; public String getId() { return id; } } //In main method somewhere Student s = new Student(); Person p = new Person(); Person q = new Person(); Faculty f = new Faculty(); Object o = new Faculty(); String n = s.getName(); // fine p = s; // fine, all student is a person int m = p.getId(); // bad, because compiler does not know that p is a student, you need to cast it as below int m = ((Student)p).getId(); f = q; // bad, not all person is a faculty o = s; //fine, anything is a objectModifiers:
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 only access from same class
一般来说,只用public和private
Revisit Constructor:
Student s = new Student();
new - allocates space
Student() is passed to constructor
From inside out:
Student() -> Person() -> Object()
Object() will initialize variables then Person(), then Student().
Compiler Rules:
1. No super class: then insert "extends Object"
2. No constructor: give one for you
2. In the constructor, the first line must be:
this(args_optional);
or super(args_optional);
If none, then compiler inserts "super();"
Method Overriding:
Override: Subclass has same method name with the same parameters as the superclass
Overload: Same class has same method name with different parameters.
No comments:
Post a Comment