上面的博文已经写了大部分了,下面这一篇博文我们主要写继承之后,父类和子类的方法的覆盖和隐藏方面。
该文章版署源自:
源自连接:https://www.cnblogs.com/dolphin0520/p/3803432.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
这道题目主要考察的是类继承时构造器的调用顺序和初始化顺序。要记住一点:父类的构造器调用以及初始化过程一定在子类的前面。由于Circle类的父类是Shape类,所以Shape类先进行初始化,然后再执行Shape类的构造器。接着才是对子类Circle进行初始化,最后执行Circle的构造器。 |
2.下面这段代码的输出结果是什么?
public class Test {
public static void main(String[] args) {
Shape shape = new Circle();
System.out.println(shape.name);
System.out.println(shape.getName());
shape.printType();
shape.printName();
}
}
class Shape {
public String name = "shape";
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
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 void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
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
circle
this is circle
shape
这道题主要考察了隐藏和覆盖的区别(当然也和多态相关)。
覆盖只针对非静态方法(终态方法不能被继承,所以就存在覆盖一说了),而隐藏是针对成员变量和静态方法的。这2者之间的区别是:覆盖受RTTI(Runtime type identification)约束的,而隐藏却不受该约束。也就是说只有覆盖方法才会进行动态绑定,而隐藏是不会发生动态绑定的。在Java中,除了static方法和final方法,其他所有的方法都是动态绑定。因此,就会出现上面的输出结果。
学习总结:假如A类被B类继承了,A类指向了创建B类的地址的时候,调用以下方面的时候实际调用的是B类中的值或者方法。
-----》A类被B类的重写的方法,在调用的时候,实际调用的是B类的方法。
(上面解析:Shape类的name,Circle类中也有,但是setName()方法重写了name的值,所以Shape类输出name的时候,调用的其实是Circle类的值。但是Shape类的name还是shape)