1.Inheritance
1.The inheritance is a crucial means in software interoperability(软件互用)
superclass
To describe something own the common fileds(属性),we create a class.
But when we need to thin(细化) this class,we need to use subclass(子类).
And generally,the subclass has these features:
a.A subclass can only inherit one superclass directly, not only one class.
b.If there exists one or more than one constructors in the superclass and these constructors have parameters. Accordingly,in the subclass,we should use super(); to inherit its parameter(s),avoiding errors.
c.the execution sequence(执行顺序) is “ superclass -> subclass A -> subclass B..."
super();
This means invoking the constructor(s) in the superclass.
superclass
public class Car{
private int wheels;
private int engines;
private String brand;
pribate String color;
public Car(int wheels){
this.wheels = wheels;
System.out.println(" A superclass constructor has been invoked.");
}
subclass
public class Audi extends Car{
public Audi(int wheels){
super(wheels);
}
}
inherit mutiple classes
Here the class C inherits the members in A & B.
public class A{
private int a;
}
public class B extends A{
private int b;
}
public class C extends B{
}
Override(重写、覆盖)
1.This work for the subclass to re-implement the method in the superclass.
Some significant characterists of this:
a.The name and parameter should be identical.
b.The scope(作用域) of modifier type in the subclass should be lagger than the superclass or the same to the superclass.
c.The scope of return value in the subclass should be smaller than the superclass or be the same.
d.The scope of "throws exception" in the subclass should be smaller than the superclass or be the same. (*** the 'Exception' & 'IOException'***)
Low coupling & High cohesion(低耦合 高内聚)
This is the principle of writing code.
The usage of inheritance is high coupling.So it sometimes will be a threat.
Because we may inadvertently invoke a null pointer.
solutions
a.Make attributes in superclass as a private type as much as possible.
b.Don't invoke any possibly overrided methods by subclass in the constructor of the superclass as much as possible.