Java Basics Part 17/20 - Methods

Java Basics Part 17/20 - Methods

目录


方法是语句的集合,用来执行一个操作。比如调用 System.out.println() 方法时,系统实际上是执行了一些语句,从而把一条消息显示到控制台。

下面就将学习在程序设计中怎样创建一个有或者无返回值的方法,怎样调用有或者无形参的方法,以及运用方法抽象。


方法创建

用一个例子来解释方法的语法:

public static int methodName(int a, int b) {
  // body
}
  • public static: 修饰符
  • int: 返回类型
  • methodName: 就是方法名称咯
  • a, b: 形参列表

方法的定义含有方法头和方法体,形式如下:

modifier returnType nameOfMethod (Parameter List) {
 // method body
}

语法解释:

  • modifier: 定义了方法的访问类型,可选
  • returnType: 定义了方法的可能的返回类型
  • nameOfMethod: 方法名。方法签名包含了方法名和参数列表
  • Parameter List: 参数列表:参数的类型,顺序,个数。这些都是可选的
  • method body: 语句的集合

举例:

/** 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; 
}

方法调用

方法的调用有两个结果:返回值和不返回值。

方法的调用很简单,当程序调用方法时,程序就把控制权交给了被调用的方法,这个方法在下面两种情况下会把控制权返还给调用者:

  • 执行了 return 语句
  • 到达了方法的末尾

举例:
下面的例子演示了方法的创建和调用

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

// output
inimum value = 6

void 关键字

如果方法不返回值,那么就用 void 关键字吧

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

// output
Rank:A1

参数传值

参数可以传值或者引用。
下面演示传值的方法

public class swappingExample {

   public static void main(String[] args) {
      int a = 30;
      int b = 45;

      System.out.println("Before swapping, a = " +
                          a + " and b = " + b);

      // Invoke the swap method
      swapFunction(a, b);
      System.out.println("\n**Now, Before and After swapping values will be same here**:");
      System.out.println("After swapping, a = " +
                         a + " and b is " + b);
   }

   public static void swapFunction(int a, int b) {

      System.out.println("Before swapping(Inside), a = " + a
                           + " b = " + b);
      // Swap n1 with n2
      int c = a;
      a = b;
      b = c;

      System.out.println("After swapping(Inside), a = " + a
                           + " b = " + b);
   }
}

// output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45

方法重载

重载,是一个类中有 2 个 或多于 2 个的同名但参数不同的方法。重载与重写不同,重写指的是类与子类的关系,重写的方法与原方法完全相同。

举例

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

// output
inimum Value = 6
inimum Value = 7.3

使用命令行参数

有时候有从外部给程序传递参数的需求。这个时候就要通过给 main() 传递命令行参数。
命令行参数是紧跟在程序名称的信息。这些参数存储在 mian() 的 String[] 参数中。

public class CommandLine {

   public static void main(String args[]){ 
      for(int i=0; i<args.length; i++){
         System.out.println("args[" + i + "]: " +
                                           args[i]);
      }
   }
}

// execute
$java CommandLine this is a command line 200 -100

// output
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

构造器

当创建对象的时候,构造器负责初始化对象。构造器的名字与类名一样。但是,构造器没有显示的返回值。

通常,通过构造器给实例变量赋初值,或者用它来创建对象。

所有的类都有构造器,即使不显示定义,Java 也会自动提供一个默认的构造器。但是一旦有了自定义的构造器,默认的构造器就不会创建了。

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

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

// call the constructor
public class ConsDemo {

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

参数化的构造器

最一般的情形是需要构造器接收 1 个 或 多个 参数。构造器接收参数和方法接收参数是一样的。

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

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

// call the constructor
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);
   }
}

// output
10 20

this 关键字

this 关键字一般用在实例方法或者构造器中,用来引用当前类的对象。使用 this,可以引用类的成员,比如构造器,变量和方法。

this 只能用在实例方法或者构造器中

通常情况下,this 用来:

  • 在构造器或者方法中,用来区分同名的局部变量和实例变量

    class Student {
    
       int age;   
    
       Student(int age){
          this.age=age; 
       }
    }
  • 在同一个类中,一个构造器调用其他构造器时。

        class Student{
           int age
    
           Student(){
               this(20);
           }
    
           Student(int age){
               this.age=age;    
           }
        }

举例:
这个例子使用 this 来访问类的成员。

public class This_Example {

   //Instance variable num
   int num=10;

   This_Example(){
      System.out.println("This is an example program on keyword this ");    
   }

   This_Example(int num){
      //Invoking the default constructor
      this();

      //Assigning the local variable num to the instance variable num
      this.num=num;    
   }

   public void greet(){
      System.out.println("Hi Welcome to Tutorialspoint");
   }

   public void print(){
      //Local variable num
      int num=20;

      //Printing the instance variable
      System.out.println("value of local variable num is : "+num);

      //Printing the local variable
      System.out.println("value of instance variable num is : "+this.num);

      //Invoking the greet method of a class
      this.greet();     
   }

   public static void main(String[] args){
      //Instantiating the class
      This_Example obj1=new This_Example();

      //Invoking the print method
      obj1.print();

      //Passing a new value to the num variable through parametrized constructor
      This_Example obj2=new This_Example(30);

      //Invoking the print method again
      obj2.print(); 
   }

}

// output
This is an example program on keyword this 
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this 
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint

变长参数

JDK 1.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);
   }
}

// output
The max value is 56.5
The max value is 3.0

finalize() 方法

有可能需要定义一个在对象的被销毁之前由垃圾回收器调用的方法。这个方法就是 finalize()。它可以用来确保对象被完全清除。

比如,可能会使用 finalize() 来确保打开的资源文件对象被关闭。

只需要在类中定义一个 finalize(),就算是给类添加了一个 finalizer (终结器?)。Java 运行时会在销毁对象之前调用它。

protected void finalize() {
   // finalization code here
}

这里使用 protected,是为了防止类的外部直接访问到 finalize()。

但是 finalize() 方法不确定会何时执行。例如,程序在垃圾回收之前就结束了,那么finalize() 就不会执行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章