Inheritance, Interface, Abstract Class
1 Inheritance(继承)
- A class that is derived from another class is called a subclass 子类 (also a derived class, extended class, or child class).
- The class from which the subclass is derived is called a superclass 父类 (also a base class or parent class)
- "龙生龙,凤生凤,老鼠的孩子会打洞" - 继承,重用
public class Person {
private String name;
public void setName(String) { this.name = name;}
public String getName() { return name; }
}
public class Employee extends Person {
private String company;
public void setCompany(String company) { this.company = company; }
public String getCompany() { return company; }
}
// Empoyee 不仅是员工也是个人,但是有新的“特性”(company name)
// 重用父类的状态
Employee e = new Empoyeee("John");
String name = e.getName();
String company = e.getCompany();
2 Override vs. Overload
- 决定我调用什么signature是在compile time
- 决定调用的函数发生什么行为是在runtime!
- 子类型同时也是父类型
2.1 Override
- Override is when you redefine a method that has been defined in a parent class (using the same signature).
- Resolved at runtime
public class Empolyee extends Person {
private String company;
// “狗皮膏药” 贴在要改的地方
@Override // better
public void setName(String name) {
thie.name = name + "," + this.company;
}
public static void main(String[] args) {
// Chris, Google ^_^
Employee e = new Employee("Chris");
e.setCompany("Google");
e.setName("Mario");
System.out.println(e.getName()); // Mario, Google
}
}
2.2 Overload
- Overload is when you define two methods with the same name, in the same class, distinguished by their signatures (different)
- Resolved at compile time
public class Empolyee extends Person {
private String company;
// Java 的 signature 是 函数名+参数类型列表!
public void setCompany(String company) {
this.company = company;
}
public void setCompany(String company, String name) {
this.name = name;
this.company = company;
}
public static void main(String[] args) {
Employee e = new Employee("Chris");
e.setCompany("Google", "Mario");
e.setCompany("Google");
System.out.println(e.getName()); // Mario, Google
}
}
2.3 Tips
- ALWAYS use @override when overriding
- Avoid dependencies from parent class to child class (定义父类型,不要牵扯入子类型)
- Use concrete results of the program to make judgements, not by you intuitions.
3 Interface vs. Abstract Class
- A class must be declared abstract (抽象) when it has one or more abstract methods.
- An abstract class may provide some methods with definitions - so an abstract class can have non-abstract methods with actual implementation details.
- An abstract class can also have constructors and instance variables as well.
- An interface can NOT provide any method definitions - it can only provide method headings.
- Any class that implements the interface is responsible for providing the method definiton/implemetation.
- A method is declared abstract when it has a method heading, but no body - which means that an abstract method has no implementation code inside like normal methods do.
public interface Employee {
// no instance-level data fields
public int calculateSalary(double performanceScore);
// no method implementation(Java8 supports default methods)
}
public abstract class Employee {
// we can have some data fields here
// constructor method OK
// method with implementation also OK
public abstrcact int calculateSalary(double performanceScore);
}
//不能直接instanciate abstract class或者interface:
Employee e = new Employee(); Wrong!!!
public class Manager extends Employee {
@Override
public int calculateSalary(double performanceScore) {
return (int) (getBaseSalary(level))*(performanceScore);
}
}
Employee e2 = new Manager(); Correct!!!
- 单继承 - Java does not allow multiple inheritance. In Java, a class can only derive from on class, wheter it's abstract or not. However, a class can implement multiple interfaces.("一人只能认一个爹!")
3.1 abstract: is a; interface: has a function
public abstract class Door {
abstract void open();
abstract void close();
}
public interface Alarm {
void alarm();
}
public class AlarmDoor extends Door implements Alarm {
void open(){...}
void close(){...}
void alarm(){...}
}
- Question: When will you use abstract class vs. interface?
- An abstract class is good if you will plan on using inheritance since it provides a common base class implementation to derived classes.
- An abstract class is also good if you want to be able to declare non-public members. In an terface, all methods must be public. If you think you will need to add methods in the future, then an abstract class is a better choice.(所有已经implement你借口的class,必须要在你加了新method后全部改变!)
- Interface is a good choice when you think that the API will not change for a while. Interface are also good when you want to have something similar to multiple inheritance, since you can implement multiple interfaces.
3.2 interface v.s. abstract class v.s. concrete class?
1 An abstract class provides a common base class implementation to derived classes. Use abstract class (or even concrete class) for base class if the derived classes share common implementation
Example Base class : House Derived class : Townhouse, SingleFamilyHouse
2 Interface helps you (or enforce you) to focus on the API signature definition.
Example interface Collection: add(E), size(), contains(Object)... Collection's subclasses may share NO common implementation at all.
3 Multiple inheritance:implementat multiole interfaces
Example ArrayList implements: Serializable, Cloneable, Iterable< E>...
4 The relationship between the interface itself and the class implementing the iterface is not necessarily strong(capability)
Example class House implements AirConditioning ArrayList implements Serializable