第八节:方法

Java 方法

一个 Java 方法是为了执行某个操作的一些语句的组合。举个例子来说,当你调用 System.out.println("字符串") 方法时,系统实际上会执行很多语句才能在控制台上输出信息。

现在你将学习怎么创建你自己的方法,他们可以有返回值也可以没有返回值,可以有参数,也可以没有参数,重载方法要使用相同的方法名称,并在程序设计中利用抽象的方法。

创建方法

我们用下面的例子来解释方法的语法

public static int funcName(int a, int b) {
  
     int i = 9;
     return i;
  }

在这里

public static:修饰符
int:返回值类型
funcName:函数名称(function)
a,b:形式参数
int a,int b:参数列
方法的定义包含方法头和方法体。如下所示:
modifier returnType nameOfMethod (Parameter List) {
 // method body
}

以上的语法包括

modifier:他定义了方法的访问类型,它是可选的。
returnType:方法是可能返回一个值的。
nameOfMethod:这是方法的名称。方法签名包括方法名称和参数列表。
Parameter List:参数列表,它是参数的次序,类型,以及参数个数的集合。这些都是可选的,当然方法也可以没有参数。

方法体:方法体定义了这个方法是用来做什么的。
示例

这是上面定义的方法max(),该方法接受两个参数num1和num2返回两者之间的最大值。

/** the snippet returns the minimum between two numbers */
public static int minFunction(int n1, int n2) {
   int min;
   if (n1 > n2)
      min = n2;
   else
      min = n1;

   return min; 
}

方法调用

要想使用一个方法,该方法必须要被调用。方法调用有两种方式,一种是有返回值的,一种是没有返回值的。

调用方法很简单,当程序需要调用一个方法时,控制程序转移到被调用的方法,方法将会返回两个条件给调用者:

返回一条执行语句
执行到方法结束
将返回void的方法作为一个调用语句,让我看下面的例子:

System.out.println("hello!");
该方法的返回值可以通过下面的例子被理解:

int result = sum(6, 9);
示例

下面的例子表明了怎么定义方法和怎么调用它:

public class ExampleMinNumber{

   public static void main(String[] args) {
      int a = 11;
      int b = 6;
      int c = minFunction(a, b);
      System.out.println("Minimum Value = " + c);
   }

   /** returns the minimum of two numbers */
   public static int minFunction(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}

将会产生如下的结果

Minimum value = 6
关键字 void

关键字 void 允许我们创建一个没有返回值的方法。这里我们在下一个例子中创建一个 void 方法 methodRankPoints。这个方法是没有返回值类型的。调用 void 方法必须声明 methodRankPoints(255.7); Java 语句以分号结束,如下所示:

public class ExampleVoid {

   public static void main(String[] args) {
      methodRankPoints(255.7);
   }

   public static void methodRankPoints(double points) {
      if (points >= 202.5) {
         System.out.println("Rank:A1");
      }
      else if (points >= 122.4) {
         System.out.println("Rank:A2");
      }
      else {
         System.out.println("Rank:A3");
      }
   }
}

这将产生如下的结果:

Rank:A1
方法的重载

当一个方法有两个或者更多的方法,他们的方法名字一样但是参数不同时,就叫做方法的重载。它与覆盖是不同的。覆盖是指方法具有相同的名字,类型以及参数的个数。

让我们来考虑之前的找最小整型数的例子。如果我们要求寻找浮点型中最小的数时,我们就需要利用方法的重载来去创建函数名相同,但参数不一样的两个或更多的方法。

下面的例子给予解释:

public class ExampleOverloading{

   public static void main(String[] args) {
      int a = 11;
      int b = 6;
      double c = 7.3;
      double d = 9.4;
      int result1 = minFunction(a, b);
      // same function name with different parameters
      double result2 = minFunction(c, d);
      System.out.println("Minimum Value = " + result1);
      System.out.println("Minimum Value = " + result2);
   }

  // for integer
   public static int minFunction(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
   // for double
   public static double minFunction(double n1, double n2) {
     double min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}

这将产生如下结果:

Minimum Value = 6
Minimum Value = 7.3
重载方法使程序易读。在这里,两种方法名称相同但参数不同。产生整型和浮点类型的最小数作为程序运行结果。

构造函数

这是一个简单的使用构造函数的例子:

// A simple constructor.
class MyClass {
   int x;

   // Following is the constructor
   MyClass() {
      x = 10;
   }
}

你可以通过以下方法来调用构造函数来实例化一个对象:

public class ConsDemo {

   public static void main(String args[]) {
      MyClass t1 = new MyClass();
      MyClass t2 = new MyClass();
      System.out.println(t1.x + " " + t2.x);
   }
}

通常,你将需要用构造函数来接受一个或多个参数。参数的传递和以上介绍的普通方法的参数传递是一样的,就是在构造函数的名字后面列出参数列表。

示例

这是一个简单的使用构造函数的例子:

// A simple constructor.
class MyClass {
   int x;

   // Following is the constructor
   MyClass(int i ) {
      x = i;
   }
}

你可以通过以下方法来调用构造函数来实例化一个对象:

public class ConsDemo {

public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
这将产生如下的结果:

10 20
可变长参数

JDK1.5 能够允许你传递可变长的同一类型的参数。用如下方法进行声明:

typeName... parameterName
方法声明时,你要在省略号前明确参数类型,并且只能有一个可变长参数,并且可变长参数必须是所有参数的最后一个。

示例

public class VarargsDemo {

   public static void main(String args[]) {
      // Call method with variable args  
      printMax(34, 3, 3, 2, 56.5);
      printMax(new double[]{1, 2, 3});
   }

   public static void printMax( double... numbers) {
   if (numbers.length == 0) {
      System.out.println("No argument passed");
      return;
   }

   double result = numbers[0];

   for (int i = 1; i <  numbers.length; i++)
      if (numbers[i] >  result)
      result = numbers[i];
      System.out.println("The max value is " + result);
   }
}

这将产生如下的结果:

The max value is 56.5
The max value is 3.0

课件代码


//  class为:类,一个.java文件里只能有一个公共类(public class)
public class People{

   // 【属性,实体变量,成员变量】
   int age;
   String color;

   /*
   
   1.通过方法的重载,一个类里可以有多个构造函数
   2. 如果不写构造函数,会默认生成 最简单的构造函数
      类名(){
  
      }
    3.构造函数需要注意:①方法名与类名一样,首字母大写
    ② 没有返回值 ③可以传若干参数(初始化对象用)
    4.构造函数的作用就是 创建对象 用的 给初始值,
    */
   // 构造函数
   People() {
      age = 10;
      color = "black";
   }
   // 方法的重载
   People(int a) {
      age = a;
      color = "white";
   }

   People(int a,String c){
    age = a;
    color = c;
   }

    /* 跳多高
      方法的修饰符 不是必须写的,取决于需要
    */
    void jump(int j){
        System.out.println("我可以跳:"+j+"米");

    }
    public static void main(String args[]) {

      // 定义一个 对象 【非常重要】.People是类,jhon jerry littleH 是对象,对象可以调用类的【方法和属性】
      People jhon = new People();
      // 通过方法的重载,调用People(int a) {...}
      People jerry = new People(20);

      People litleH = new People(23,"blue");

      litleH.jump(3);

      System.out.println(" litleH: "+litleH.age + " " + litleH.color);
      System.out.println(" jerry: "+jerry.age + " " + jhon.color);
      System.out.println(" jhon: "+jhon.age + " " + jhon.color);
   }

}
// 一个.java 文件中可以有多个class,但是只能有一个public clss
 class Women{ 
  

}

class Men{

  
}


public class UserString{

    public static void main(String[] args) {
        
      UserString us = new UserString();
      int [] arrList = {19,3,22,28,32};
      int reslut = us.max(arrList);
      System.out.print(reslut);


    }

   /*
      function:比较两个数的大小
      param: int x, int y
      return: int 比较结果 
    */
   public  int[] max(int[] arr){

     int max = arr[0];

     for (int x : arr) {
        
        if (x > max) {
           max = x;
        }
     }
     return max;

   }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 3,275评论 0 4
  • C++运算符重载-下篇 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符和二元逻辑运算符4...
    Haley_2013阅读 1,485评论 0 49
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,099评论 19 139
  • 每到夏天,姐妹们最欢喜的无非是穿上自己最喜欢的裙子、短裤,既彰显了女性魅力,又很是凉爽。着装上彻底的,很轻松的感觉...
    0061澳洲制造阅读 235评论 0 0