继承类
- 被重写的方法名称必须跟父类保持一致
- 重写的方法中参数列表必须跟父类方法一直(否则就不叫重写而是重载) 3. 子类调用的方法是被重写过之后的方法(并非父类的方法) 4. 被重写的方法返回值类型必须跟父类保持一致
- 被重写的方法访问权限不能小于父类(不含private)
- 私有方法不能被重写
- 所谓重写就是对方法的实现体重新实现
- package father;
public class Animal {
double weight;
String name;
protected double getWeight() {
return weight;
}
protected void setWeight(double weight) {
this.weight = weight;
}
protected String getName() {
return name;
}
protected void setName(String name) {
this.name = name;
}
}
package father;
public class Mouse extends Animal {
public Mouse(String name, double weight) {
// TODO Auto-generated constructor stub
}
public void runway() {
// TODO Auto-generated method stub
System.out.println(this.getName()+"逃跑成功");
}
}
package father;
public class Cat extends Animal {
public Cat(String name, double weight) {
// TODO Auto-generated constructor stub
}
public void catchMouse(Mouse m) {
//获取猫的体重
double cw= this.getWeight();
//获取老鼠体重
double mw= m.getWeight();
if(cw<=mw*5) {
this.setWeight(cw+mw/2);
System.out.println(this.getName()+“抓住了”+m.getName());
}else {
m.runway();
}
}
}