zoukankan      html  css  js  c++  java
  • 【转】 Java多态特性:重载和覆写的比较

    Java重载:

    • 在同一个类中
    • 方法具有相同的名字,相同或不同的返回值,但参数不同的多个方法(参数个数或参数类型)
    public class MethoDemo{
        public static void main(String args[]){
            int one = add(10,20) ;        // 调用整型的加法操作
            float two = add(10.3f,13.3f) ;    // 调用浮点数的加法操作
            int three = add(10,20,30) ;    // 调用有三个参数的加法操作
            System.out.println("add(int x,int y)的计算结果:" + one) ;
            System.out.println("add(float x,float y)的计算结果:" + two) ;
            System.out.println("add(int x,int y,int z)的计算结果:" + three) ;
        }
        // 定义方法,完成两个数字的相加操作,方法返回一个int型数据
        public static int add(int x,int y){
            int temp = 0 ;            // 方法中的参数,是局部变量
            temp = x + y ;            // 执行加法计算
            return temp ;            // 返回计算结果
        }
        public static int add(int x,int y,int z){
            int temp = 0 ;            // 方法中的参数,是局部变量
            temp = x + y + z ;            // 执行加法计算
            return temp ;            // 返回计算结果
        }
        // 定义方法,完成两个数字的相加操作,方法的返回值是一个float型数据
        public static float add(float x,float y){
            float temp = 0 ;        // 方法中的参数,是局部变量
            temp = x + y ;            // 执行加法操作
            return temp ;            // 返回计算结果
        }
    };

    输出结果:

    add(int x,int y)的计算结果:30

    add(float x,float y)的计算结果:60

    add(int x,int y,int z)的计算结果:23.6

    Java覆写:

    • 子类覆写父类的方法,在不同的类中
    • 重写方法必须和被重写方法具有相同方法名称、参数列表和返回类型
    • 重写方法不能使用比被重写方法更严格的访问权限
    class Person{        // 定义父类
        void print(){    // 默认的访问权限
            System.out.println("Person --> void print()。") ;
        }
    };
    class Student extends Person{    // 定义继承关系
        public void print(){
            System.out.println("Student --> void print()。") ;
        }
    };
    public class OverrideDemo{
        public static void main(String args[]){
            Student s = new Student() ;
            s.print() ;
        }
    };

    输出结果:

    Student --> void print()。

    小结:

    java的三大特性:封装,继承,多态.而方法的重载和覆写正是多态的体现.

  • 相关阅读:
    错误: error C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. 的处理方法
    C语言习题
    嵌入式芯片STM32F407
    c语言课后习题
    求方程式的根
    C语言课后习题
    LINUX常用指令
    在 pythonanywhere 上搭建 django 程序(Virtualenv+python2.7+django1.8)
    Git远程操作详解
    ./configure,make,make install的作用
  • 原文地址:https://www.cnblogs.com/modou/p/9736455.html
Copyright © 2011-2022 走看看