Java-多态

100 阅读1分钟

多态

介绍:通俗来说,就是多种形态,具体点就是去完成某个行为,当不同的对象去完成时会产生出不同的状态。
分类:编译时多态,运行时多态

//Animal.java 父类
public class Animal {
    private String name;
    private int age;
    
    public Animal() {}
    
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    public void setAge(int age) {
        this.name = name;
    }
    
    public String getAge() {
        return name;
    }
    
    //父类的吃东西方法
    public void eat() {
        System.out.printl("父类的吃东西方法");
    }
}
//Cat.java 子类
public class Cat extends Animal {
    private double weight;
    
    public Cat() {}
    
    public Cat(String name, int age, double weight) {
        super(name, age);
        this.weight = weight;
    }
    
    public void setWeight(double weight) {
        this.weight = weight;
    }
    
    public double getWeight() {
        return weight;
    }
    
    //子类独有的方法
    public void run() {
        System.out.printl("子类独有的跑动方法");
    }
    
    //重新父类的吃东西方法
    @override
    public void eat() {
        System.out.printl("子类的吃东西方法-猫");
    }
}
//Dog.java 子类
public class Dog extends Animal {
    private String sex;
    
    public Dog() {}
    
    public Dog(String name, int age, String sex) {
        super(name, age);
        this.sex = sex;
    }
    
    public void setSex(String sex) {
        this.sex = sex;
    }
    
    public double getSex() {
        return sex;
    }
    
    //子类独有的方法
    public void sleep() {
        System.out.printl("子类独有的睡觉方法");
    }
    
    //重新父类的吃东西方法
    @override
    public void eat() {
        System.out.printl("子类的吃东西方法-狗");
    }
}
//Test.java 测试类
public class Test {
    public static void main(String[] args) {
        Animal one = new Animal();
        //向上转型、隐式转型、自动转型 -> 父类引用指向子类,可以调用父类的派生方法,无法调用子类的独有方法
        Animal two = new Cat();
        Animal three = new Dog();
        
        one.eat();
        two.eat();
        three.eat();
        
        //向下转型、强制类型转换 -> 子类引用指向父类,必须进行强转,可以调用子类特有的方法
        Cat temp = (Cat)two;
        temp.eat();
    }
}

instanceof运算符:用于测试对象是否是指定类型(类或子类或接口)的实例

//判断左边的对象是否是右边的实例
if(two instanceof Dog) {
    //满足返回true
} else {
    //不满足返回false
}