面向对象——多态
        【摘要】 基本介绍        方法或者对象具有多种形态。是面向对象的第三大特征,多态是建立在封装和继承基础上的。方法的多态public class PolymorphicMethod {    public static void main(String[] args) {        //方法重载体现多态        B b = new B();        //这里传入不同的参数,就会调...
    
    
    
    基本介绍
方法或者对象具有多种形态。是面向对象的第三大特征,多态是建立在封装和继承基础上的。
方法的多态
public class PolymorphicMethod {
    public static void main(String[] args) {
        //方法重载体现多态
        B b = new B();
        //这里传入不同的参数,就会调用不同的方法
        System.out.println(b.sum(10, 20));
        System.out.println(b.sum(10, 20, 30));
        System.out.println("===========");
        //方法重写体现多态
        A a = new A();
        a.say();
        b.say();
    }
}
class A {
    public void say() {
        System.out.println("A类的say()方法被调用。。。");
    }
}
class B extends A {
    public void say() {
        System.out.println("B类的say()方法被调用。。。");
    }
    public int sum(int n1, int n2) {
        return n1 + n2;
    }
    public int sum(int n1, int n2, int n3) {
        return n1 + n2 + n3;
    }
}
输出结果:
 对象的多态
(1)一个对象的编译类型和运行类型可以不一致
例如:Animal animal = new Dog(); 可以让一个对象父类的引用指向子类的一个对象(animal的编译类型是Animal,运行类型是Dog)
(2)编译类型在定义对象时就确定了,不能改变
(3)运行类型是可以改变的
即:animal = new Cat();(animal的运行类型变成了Cat,编译类型仍然是Animal)
(4)编译类型看定义时 = 号的左边,运行类型看 = 号的右边
基本案例演示
public class PolymorphicObject {
    public static void main(String[] args) {
        Animal animal = new Dog();//animal 的编译类型是Animal,运行类型是Dog
        animal.cry();//小狗汪汪叫
        //执行到animal.cry();时,animal的运行类型是Dog,所以cry就是Dog类的方法
        animal = new Cat();//animal 的编译类型还是Animal。运行类型变为了Cat
        animal.cry();//小猫喵喵叫
    }
}
class Animal {
    public void cry() {
        System.out.println("动物在叫。。。");
    }
}
class Dog extends Animal {
    public void cry() {
        System.out.println("小狗汪汪叫。。。");
    }
}
class Cat extends Animal {
    public void cry() {
        System.out.println("小猫喵喵叫。。。");
    }
}
        
            【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
                cloudbbs@huaweicloud.com
                
            
        
        
        
        
        
        
        - 点赞
 - 收藏
 - 关注作者
 
            
           
评论(0)