zoukankan      html  css  js  c++  java
  • java方法、方法重载

     

    java方法

    一、Java方法

    1. 方法声明

    [修饰符1 修饰符2 ...]  返回值类型  方法名(形式参数列表) {
        语句...  
    }

    2. 方法调用

    对象名.方法名(实际参数);
     1 public class TestMethod {
     2     public static void main(String args[]) {
     3         printInfo();
     4         int num1 = 2020;
     5         int num2 = 30;
     6         System.out.printf("%d + %d = %d", num1, num2, add(num1, num2));
     7     }
     8 
     9     public static int add(int a, int b) {
    10         return a + b;
    11     }
    12 
    13     public static void printInfo() {
    14         System.out.println("步平凡的博客>>>");
    15     }
    16 }

    二、Java方法重载

    1. 方法重载与方法的区别

      就上方的加法函数add()而言,若想要完成三个数或多个数的加法时,此时就用到方法重载了。

      方法重载可以理解为方法的拓展。

    2. 方法重载的条件

      方法重载的名字与原方法名相同,但形式参数列表不同,此处不同体现为参数类型、参数个数。

      更好的理解,看看下面代码吧~~~

    public class TestMethodPro {
        public static void main(String args[]) {
            System.out.printf("1 + 2 = %d
    ", add(1, 2));         // 调用方法1
            System.out.printf("1 + 2 + 0 = %d
    ", add(1, 2, 0));  // 调用方法2
            System.out.printf("1.0f + 2 = %d
    ", add(1.0f, 2));   // 调用方法3
            System.out.printf("1 + 2.0 = %d
    ", add(1, 2.0));     // 调用方法4
        }
        
        public static int add(int a, int b) { // 方法1
            return a + b;
        }
    
        public static int add(int a, int b, int c) { // 方法2
            return a + b + c;
        }
    
        public static int add(float a, int b) { // 方法3
            return (int)(a + b);
        }
    
        public static int add(int a, double b) { // 方法4
            return (int)(a + b);
        }
    }

  • 相关阅读:
    docker知识集锦
    kubernetes知识集锦
    redis知识集锦
    Java多线程知识集锦
    vscode离线安装插件
    jsoncpp的简易教程
    为什么要自动化测试?
    如何选择正确的自动化测试工具
    如何选择测试自动化工具?
    测试自动化的五大挑战
  • 原文地址:https://www.cnblogs.com/bpf-1024/p/12650581.html
Copyright © 2011-2022 走看看