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);
        }
    }

  • 相关阅读:
    node 中的 异步地狱回调
    node 同步和异步的概念
    【Node】File System
    阅读《软技能:代码之外的生存指南》读书笔记
    整理前端学习资料以便日后查看
    【css】单选框和复选框文字垂直居中问题
    [CSS]图片与文字对齐问题--摘自张鑫旭博客
    百度首页换一换功能js实现
    个人加分项
    开课第十五周周总结
  • 原文地址:https://www.cnblogs.com/bpf-1024/p/12650581.html
Copyright © 2011-2022 走看看