美文网首页
JAVA重载

JAVA重载

作者: 躺在家里干活 | 来源:发表于2019-10-08 09:50 被阅读0次
    package com.generator;
    
    public class TestOverload {
    
        void sayHello(Human human) {
            System.out.println("Human");
        }
    
        void sayHello(Man human) {
            System.out.println("man");
        }
    
        void sayHello(Woman human) {
            System.out.println("Woman");
        }
    
        public static void main(String[] args) {
            Man man = new Man();
            Human man2 = new Man();
            Woman woman = new Woman();
            Human woman2 = new Woman();
            TestOverload testOver = new TestOverload();
            testOver.sayHello(man);
            testOver.sayHello(man2);
            testOver.sayHello(woman);
            testOver.sayHello(woman2);
        }
    }
    
    class Human {
    }
    
    class Man extends Human{
    }
    
    class Woman extends Human{
    }
    
    class Child extends Human{
    }
    
    

    运行结果:

    man
    Human
    Woman
    Human
    

    结论:
    虚拟机在重载时是通过参数的静态类型而不是实际类型判断重载方法的。Human man = new Man()Human是静态类型,Man是实际类型

    相关文章

      网友评论

          本文标题:JAVA重载

          本文链接:https://www.haomeiwen.com/subject/aqwiyctx.html