Java 基础 4

继承

Java 中所有的类的祖先都是 Object,在定义类的层次结构时,可以把一些类的相同点抽象出来,作为父类,减少代码重复。

如定义一个 Animal 类:

public class Animal {
  public void roam() {
    // do some thing
    System.out.println("Animal roam");
  }
}

当一个类 Dog 继承自 Animal 时,Dog 就默认拥有了 roam 方法:

public class Dog extends Animal {

}
Dog d = new Dog();
d.roam(); // output: Animal roam

子类可以覆写父类的同名方法,从而使函数实现不同的功能

public class Cat extends Animal {
  public void roam() {
    System.out.println("Miao");
  }
}
Cat c = new Cat();
c.roam();  // output: Miao

在子类覆写父类的同名方法中,仍然可以调用父类的同名方法

public void roam() {
  super.roam();
  System.out.println("Miao");
}
Cat c = new Cat();
c.roam(); // output: Animal roam \n Miao

super 关键字和 this 关键字类似,super 可以调用父类的相应方法(包括构造函数)或使用父类的成员变量(非 private),this 可以调用当前类的方法或使用当前类的成员变量。

在构造函数中,super() 或者 this() 的调用必须放在方法体的第一行,否则无法编译。

public class Cat extends Animal {
  public Cat() {
    super(); // 默认行为,不写时,编译器默认添加该语句
  }    
}

 

重新定义 Animal 和 Cat,

class Animal {
  public Animal() {
    System.out.println("Constructor of animal");
  }
}

public class Cat extends Animal {
  public Cat() {
    System.out.println("Constructor of cat");
  }
  public Cat(String name) {
    this();
    System.out.println("Miao, " + name);
  }
}

调用 Cat 的两种构造函数:

Cat c = new Cat();
// output:
// Constructor of animal
// Constructor of cat

 

Cat c = new Cat("d");
// output:
// Constructor of animal
// Constructor of cat
// Miao, d

 

使用 this() 调用类的其它构造函数时,super() 就不会添加到构造函数的第一行。即 this() 和 super() 在一个构造函数中只能出现一次。

但由于被调用的构造函数总会被编译器添加上 super(),因此父类的构造方法还是会执行。

 

posted @ 2021-02-03 12:56  山__河  阅读(99)  评论(0)    收藏  举报