Java中super()和this()之间的区别
以下是Java中super()
和this()
方法之间的显着区别。
示例
class Animal { String name; Animal(String name) { this.name = name; } public void move() { System.out.println("Animals can move"); } public void show() { System.out.println(name); } } class Dog extends Animal { Dog() { //用它来调用当前的类构造器 this("Test"); } Dog(String name) { //使用super调用父构造函数 super(name); } public void move() { //调用超类方法 super.move(); System.out.println("Dogs can walk and run"); } } public class Tester { public static void main(String args[]) { //动物参考但狗对象 Animal b = new Dog("Tiger"); b.show(); //在Dog类中运行方法 b.move(); } }
输出结果
Tiger Animals can move Dogs can walk and run