多态
1.向上转型、隐式转型、自动转型
父类引用指向子类实例,可以调用子类重写父类的方法以及父类派生的方法,无法调用子类独有方法
注意:父类中的静态方法无法被子类重写,所以向上转型之后,只能调用到父类原有的静态方法,想要调用子类中的静态方法需要重新向下造型
小类转型为大类
2.向下转型、强制类型转换
子类引用指向父类对象,此处必须进行强转,可以调用子类特有的方法
必须满足转型条件才能进行强转
instanceof运算符:返回true/false
3.代码如下
package com.liuermeng.animal;
public class Animal {
//属性:昵称、年龄
private String name;
private int month;
public Animal(){
}
public Animal(String name,int month){
this.name=name;
this.month=month;
}
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 void eat() {
System.out.println("动物都爱吃东西");
}
//父类中的静态方法
public static void say(){
System.out.println("动物们都会打招呼");
}
}
package com.liuermeng.animal;
public class Cat extends Animal {
//属性:体重
private double weight;
public Cat(){
}
public Cat(String name,int month,double weight){
super(name,month);
// this.setMonth(month);
this.weight=weight;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
//方法:跑动
public void run(){
System.out.println("小猫快乐的奔跑");
}
//方法:吃东西(重写父类方法)
@Override
public void eat() {
System.out.println("猫吃鱼~~");
}
//子类中也定义一个相同的static方法。注意这个不是重写,是与父类中方法无关的另一个静态方法
public static void say(){
System.out.println("小猫碰胡须");
}
}
package com.liuermeng.animal;
public class Dog extends Animal {
//属性:性别
private String sex;
public Dog(){
}
public Dog(String name,int month,String sex){
this.setMonth(month);
this.setName(name);
this.setSex(sex);
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
//方法:睡觉
public void sleep(){
System.out.println("小狗有午睡的习惯");
}
//方法:吃东西(重写父类方法)
@Override
public void eat() {
System.out.println("狗吃肉~~");
}
}
package com.liuermeng.test;
import com.liuermeng.animal.Animal;
import com.liuermeng.animal.Cat;
import com.liuermeng.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
two.eat();
two.say();
// two.run();//会报错
Cat cat=(Cat)two;
System.out.println("=================");
/*向下转型、强制类型转换
* 子类引用指向父类对象,此处必须进行强转,可以调用子类特有的方法
* 必须满足转型条件才能进行强转
* instanceof运算符:返回true/false
*/
if(two instanceof Cat){
Cat temp=(Cat)two;
temp.eat();
temp.run();
temp.getMonth();
System.out.println("two可以转换为Cat类型");
}
if(two instanceof Dog){
Dog temp2=(Dog)two;
temp2.eat();
temp2.sleep();
temp2.getSex();
System.out.println("two可以转换为Dog类型");
}
if(two instanceof Animal){
System.out.println("Animal");
}
if(two instanceof Object){
System.out.println("Object");
}
}
}
输出
猫吃鱼~~
动物们都会打招呼
=================
猫吃鱼~~
小猫快乐的奔跑
two可以转换为Cat类型
Animal
Object