class Insect {
private int size;
private String color;
public Insect(int size, String color) {
this.size = size;
this.color = color;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void move() {
System.out.println("Move");
}
public void attack() {
move(); //假设昆虫在攻击前必须要先移动一次
System.out.println("Attack");
}
}
/////子类
class Bee extends Insect {
public Bee(int size, String color) {
super(size, color);
}
public void move() {
System.out.println("Fly");
}
public void attack() {
move();
super.attack();//调用了父类的attack,但是调用了子类的move()
}
}
public class InheritanceVSComposition {
public static void main(String[] args) {
Insect i = new Bee(1, "red");
i.attack();
}
}
输出结果为:
Fly
Fly
Attack
第47行,super.attack();为什么是调用了子类的move()而不是父类的?能解释下原理吗?
子类覆写父类的方法,因为调用是从子类发出的,因此在父类中还是调用的子类的move方法;
再说this问题,this也是一个对象,但是不要将this理解成Inspect对象,this还是指的是调用者Bee的对象,你可以在调用this.move()方法前,打印一下,比如
System.out.print(this);
super的用法 构造器和方法,都用关键字super指向超类,但是用的方法不一样。方法用这个关键字去执行被重载的超类中的方法。看下面的例子: class Mammal { void getBirthInfo() { System.out.println("born alive."); } } class Platypus extends Mammal { void getBirthInfo()......
答案就在这里:java中super的用法
----------------------Hi,地球人,我是问答机器人小S,上面的内容就是我狂拽酷炫叼炸天的答案,除了赞同,你还有别的选择吗?
super代表父类啊!所以是调用父类的啊!this代表本类
i是子类Bee的实例,子类Bee重写了move()方法。
super 和this 一样,区别在于super代表父类 ,this代表当前类,
super 和this 一样,区别在于super代表父类 ,this代表当前类,
调用了父类的attack函数,attack函数里面的move函数被子类重写了,所以输出还是fly,你把父类attack的move函数改成this.move试试看(我也刚学Java,只是交流意见)。
public void attack() {
move(); //就是this.move();
System.out.println("Attack");
}
调用super.attack(); 时,
attack方法中的this是指向子类(因为是子类调用的),而不是父类.
attack方法中的this是指向引用对象,即现在是什么类型,就访问哪种类型