参考博文:
https://www.cnblogs.com/dolphin0520/p/3803432.html 讲的是继承
https://www.cnblogs.com/it12345/p/5221673.html 讲的是覆盖和隐藏
下面是两个比较好的例子~
子类继承父类后都是先运行父类的构造方法,然后在运行子类的构造方法。列如下:
public class Test {
public static void main(String[] args) {
new Circle();
}
}
class Draw {
public Draw(String type) {
System.out.println(type+" draw constructor");
}
}
class Shape {
private Draw draw = new Draw("shape");
public Shape(){
System.out.println("shape constructor");
}
}
class Circle extends Shape {
private Draw draw = new Draw("circle");
public Circle() {
System.out.println("circle constructor");
}
}
输出结果:
shape draw constructor
shape constructor
circle draw constructor
circle constructor
但是在java继承里有覆盖和隐藏的问题:例如下面:
public class Test {
public static void main(String[] args) {
Shape shape = new Circle();
System.out.println(shape.name);
shape.printType();
shape.printName();
}
}
class Shape {
public String name = "shape";
public Shape(){
System.out.println("shape constructor");
}
public void printType() {
System.out.println("this is shape");
}
public static void printName() {
System.out.println("shape");
}
}
class Circle extends Shape {
public String name = "circle";
public Circle() {
System.out.println("circle constructor");
}
public void printType() {
System.out.println("this is circle");
}
public static void printName() {
System.out.println("circle");
}
}
输出结果是:
shape constructor
circle constructor
shape
this is circle
shape
我猜在运行:shape.printType()的时候你一定会认为运行的结果是thie is shape
但是这里由于继承存在隐藏和覆盖的问题:
覆盖只针对非静态方法
隐藏是针对成员变量和静态方法
由于printType()不是成员变量也不是静态方法所以他就被父类覆盖了