知识总结:
父类:
Animal.java:
package com.imooc.animal;
public class Animal {
private String name;
private int month;
public Animal(){
}
public Animal(String name,int month){
this.setName(name);
this.setMonth(month);
}
//eat()
public void eat(){
System.out.println("动物都又吃东西的能力!");
}
//getter/setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
}
Cat.java:
package com.imooc.animal;
public class Cat extends Animal {
private String name;
private int month;
private double weight;
public Cat(){
}
public Cat(String name,int month,double weight){
super(name,month);//super父类属性构造方法赋值
setWeight(weight);
}
//run
public void run(){
System.out.println("猫会跑");
}
//方法重写
@Override
public void eat() {
System.out.println("猫吃鱼!");
}
//getter/setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
Dog.java:
package com.imooc.animal;
public class Dog extends Animal {
private String name;
private int month;
private String sex;
public Dog(){
}
public Dog(String name,int month,String sex){
super(name,month);
this.setSex(sex);
}
//sleep
public void sleep(){
System.out.println("小狗会午睡");
}
//方法重写
@Override
public void eat() {
System.out.println("狗吃肉!");
}
//getter/setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
test.java:
package com.imooc.test;
import com.imooc.animal.Animal;
import com.imooc.animal.Cat;
import com.imooc.animal.Dog;
public class test {
public static void main(String[] args) {
Animal one=new Animal();//1
/*
* 向上转型(隐式转型),自动转型
* 父类引用指向子类的实例,可以调用子类重写父类的方法以及父类的派生方法,但是该对象无法调用子类独有的方法
* 注意:父类中的静态方法无法被子类重写,所以向上转型之后,只能调用父类原油的的静态方法
* 小类转大类
*/
Animal two=new Cat();//2
Animal three=new Dog();//3
one.eat();
two.eat();
three.eat();
two.setMonth(3);
two.getMonth();
three.setName("花花");
three.getName();
//two.run();编译错误
//three.sleep();编译报错
}
}
向上转型也可以写成: