Seen the introduction of this method of Java, it will not look the other (refined version)

Star class:


Methods now come to you on the Java:
Examples: Look System.out.println (); then what is it?
println () is a method for
the System. The system is based
out standard output object.
Translation: The method println system call system class objects out of the standard output ();

java method Introduction:

Java method is a collection of statements , together they perform a function.

  • • The method is an ordered combination of steps to solve a class of problems
  • • method included in the class or object
  • • The method was created in the program, was quoted elsewhere
Advantage of the

• 1. making the program more brief and clear.
• 2. conducive to the maintenance program.
• 3. can improve the efficiency of program development.
• 4. improve the reusability of code.

Naming method

• 1. The name of the method of the first word should begin with a lowercase letter, followed by a word beginning with a capital letter is written, without the use of connectors. For example: addPerson.
• 2. underscore the logical components used in the JUnit test method names in separate names may occur. A typical pattern is: test_, e.g. testPop_emptyStack.

Defined methods

Generally, the following syntax to define a method comprising:

修饰符 返回值类型 方法名(参数类型 参数名){ ... 方法体 ... return 返回值; }

The method comprises a first method and a method thereof. Here are all part of a process:
• modifier : modifier, which is optional, to tell the compiler how to call the method. It defines the access type of the method.
• Return Value Type : method might return value. returnValueType method return value data type. Some methods perform the required operation, but no return value. In this case, returnValueType keyword void.
• Method name : is the actual name of the method. Method name and parameter list together constitute the method signature.
• Parameter type : parameter like a placeholder. When the method is invoked, the parameter value passed. This value is referred to as a variable or argument. Parameter list is the number of parameters of the type of method, and the order of the parameters. Parameter is optional, the method may not contain any parameters.
• method body : the body contains specific method statements, the definition of the function of the method.
Here Insert Picture Description
Such as:

public static int age(int birthday){...}

There can be multiple parameters:

static float interest(float principal, int year){...}

Note: In some other languages ​​refer to the process methods and functions. A non-void return type of the function return values ​​are known methods; a void return type of the method is called a return process.

Examples

The method comprises the following two parameters num1 and num2, it returns the maximum of the two parameters.
/ ** returns two integer variables large value data * /

public static int max(int num1, int num2) { 
 int result;
  if (num1 > num2)
   result = num1;
    else result = num2;
     return result;
      }
     

Method Invocation

Java supports two ways of calling methods, depending on whether the method returns a value to select.
When the program calls a method, a program to control the method is called. When the called method's return statement is executed or method to reach the body when closing parenthesis return control to the program.
When the method returns a value, the method calls are usually treated as a value. E.g:

int larger = max(30, 40);

If the method return value is void, the method call must be a statement. For example, the method println returns void. The following is a statement calling:

System.out.println("欢迎访问星星课堂");

Examples

The following example demonstrates how to define a method, and how to call it:
TestMax.java file code:

public class TestMax { 
/** 主方法
 */
 public static void main(String[] args) {
  int i = 5;
   int j = 2; 
   int k = max(i, j);
    System.out.println( i + " 和 " + j + " 比较,最大值是:" + k); 
    }
     /** 返回两个整数变量较大的值
      */
      public static int max(int num1, int num2) {
       int result; 
       if (num1 > num2) {
       result = num1; 
       else result = num2;
       return result;
        } 
        }

The above examples compiled results are as follows:

52 比较,最大值是:5

The program includes a main method and a method of max. The main method is invoked JVM, in addition, main and other methods no difference.
head main method is the same type of parameters, such as the example shown, with modifiers public and static, void return type value, is the main method name, in addition with a a String []. String [] indicates that the parameter is an array of strings.


void keyword

This section explains how to declare and call a void method.
The following example declares a named printGrade method, and call it to print a given score.
Examples
TestVoidMethod.java file code:

public class TestVoidMethod {
 public static void main(String[] args) { printGrade(78.5); 
 } 
 public static void printGrade(double score) {
  if (score >= 90.0) {
   System.out.println('A');
    } else if (score >= 80.0) {
     System.out.println('B'); 
     } 
     else if (score >= 70.0) {
      System.out.println('C');
       } else if (score >= 60.0) {
        System.out.println('D');
         } else { 
         System.out.println('F');
          }
         }
         }

The above examples compiled results are as follows:

C

Here printGrade is a void type method, it does not return a value.
A void method call must be a statement. So, it is called to statements form the main method in the third row. Like any statement ends with a semicolon like.


Argument passed by value
call when needed to provide a method parameters, you must provide a list of parameters specified in the order.
For example, the following method for continuously printing a message n times:
TestVoidMethod.java file code:

public static void nPrintln(String message, int n) {
 for (int i = 0; i < n; i++) {
  System.out.println(message);
   } 
   }

Example
The following example shows the effect of passing by value.
The program creates a method for the exchange of two variables.
TestPassByValue.java file code:

public class TestPassByValue { 
public static void main(String[] args) { 
int num1 = 1;
 int num2 = 2;
  System.out.println("交换前 num1 的值为:" + num1 + " ,num2 的值为:" + num2);
   // 调用swap方法
    swap(num1, num2);
     System.out.println("交换后 num1 的值为:" + num1 + " ,num2 的值为:" + num2);
      } 
      /** 交换两个变量的方法 
      */
       public static void swap(int n1, int n2) { System.out.println("\t进入 swap 方法"); System.out.println("\t\t交换前 n1 的值为:" + n1 + ",n2 的值:" + n2);
        // 交换 n1 与 n2的值 int
         temp = n1; 
         n1 = n2;
          n2 = temp;
           System.out.println("\t\t交换后 n1 的值为 " + n1 + ",n2 的值:" + n2); 
           } 
           }

The above examples compiled results are as follows:

交换前 num1 的值为:1 ,num2 的值为:2
    进入 swap 方法
        交换前 n1 的值为:1,n2 的值:2
        交换后 n1 的值为 2,n2 的值:1交换后 num1 的值为:1 ,num2 的值为:2

Pass two parameters to call swap method. Interestingly, after the method is called, the value of the argument has not changed.


Overloaded methods

Max method used above only applies to an int. But if you want to get the maximum value of two floating-point data type it?
Another solution is to create the same name but different parameters of the method, as shown in the following code:

public static double max(double num1, double num2) {
 if (num1 > num2) {
 
 return num1;
 }
  else
   return num2;
   }

If you transfer the call to max method it is an int parameter, max method is int argument is invoked;
if you pass a double argument is of type double max method is called experience, this is called method overloading;
that is, He said two methods of a class have the same name, but with different parameter list.
Java compiler according to the method signature to determine which method should be called.
Method overloading can make the program more legible. The method of execution is closely related tasks should use the same name.
Overloaded methods must have different parameter list. You can not just based on different types of modifiers or return to overloaded methods.


Variable Scope

Range variable is the variable part of the program can be referenced.
Variables defined in the method is known as local variables.
Scope of a local variable declarations from the start until the end of the block containing it.
Local variables must be declared before they can be used.
The method of covering the entire range of parameters method. Parameter is actually a local variable.
The loop initialization portion for variable declarations, the entire cycle of its scope.
But the scope of the variables within the loop body from its claim is declared to the end of the loop. It includes variable declarations as shown below:

You may be a method where different non-multiple nested block declaration a local variable with the same name, but you can not nest in the two local variable declaration block.
Use command line parameters
Sometimes you want to run a program when it then passed the message. It depends on passing command-line arguments to the main () function to achieve.
Command line argument is followed by information on the implementation of the program when behind the program name.
Examples
The following program prints all the command-line parameters:
CommandLine.java file code:

public class CommandLine {
 public static void main(String args[]){ 
 for(int i=0; i<args.length; i++){ System.out.println("args[" + i + "]: " + args[i]); 
 }
  }
  }
如下所示,运行这个程序:
$ javac CommandLine.java 
$ java CommandLine this is a command line 200 -100
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

Construction method

When an object is created when the method is used to initialize the object constructor. The method of construction in the name of the class and it is the same, but no return value constructor.
Typically using a constructor for the class instance variable initial value, or perform other steps necessary to create a complete object.
Whether you custom constructor, all classes have constructor, because Java automatically provides a default constructor, the default constructor same access modifier and class access modifier (class public, but also for the public constructor ; class to private, the constructor changed to private).
Once you have defined your own constructor, the default constructor will fail.
Examples
The following is an example of using the constructor:

// 一个简单的构造函数
 class MyClass {
  int x;
   // 以下是构造函数
    MyClass() { x = 10;
     } 
     }
你可以像下面这样调用构造方法来初始化一个对象:
ConsDemo.java 文件代码:
public class ConsDemo {
 public static void main(String args[]) {
  MyClass t1 = new MyClass(); 
  MyClass t2 = new MyClass();
   System.out.println(t1.x + " " + t2.x);
    } 
    }

Most of the time need to have a constructor parameter.
Examples
The following example is a method of using the constructor:
// constructor a simple
class MyClass {int X;
// The following is the constructor
MyClass (I int) = X {I;
}
}
You can call this method configured as follows initialize an object:
ConsDemo.java file code:
public class ConsDemo {public static void main (String args []) {
MyClass new new MyClass = T1 (10);
MyClass T2 = new new MyClass (20 is); System.out.println (T1 + .x "" + t2.x);
}
}
results are as follows:
10 20
variable parameters
JDK 1.5 starts, Java supports the same type of variable parameters passed to a method.
: Declare variable parameter method shown below
typeName ... parameterName
method declaration, add a parameter type specified in the ellipsis (...).
A method can only specify one variable parameter, it must be the last argument of the method. Any common parameters must be declared before it.
Examples
VarargsDemo.java file code:

public class VarargsDemo { 
public static void main(String 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 above examples compiled results are as follows:

The max value is 56.5The max value is 3.0

finalize () method

Java allows definition of such a method, which is called before the object destructor garbage collector (recycling), this method is called Finalize (), which is used to clear the recovered objects.
For example, you can use the finalize () to ensure that a subject open file was closed.
In finalize () method, you must specify the operation to be performed when the object is destroyed.
finalize () format is typically:
protected void finalize () {} // end here the code
key protected is a qualifier, it ensures finalize () method will not be called code outside the class.
Of course, Java's garbage collection can be done automatically by the JVM. If you use the manual, you can use the above method.
Examples
FinalizationDemo.java file code:

public class FinalizationDemo { 
public static void main(String[] args) {
 Cake c1 = new Cake(1); 
 Cake c2 = new Cake(2);
  Cake c3 = new Cake(3); 
  c2 = c3 = null; System.gc(); 
  //调用Java垃圾收集器
   } 
   }
    class Cake extends Object {
     private int id;
      public Cake(int id) { 
      this.id = id;
       System.out.println("Cake Object " + id + "is created");
        }
         protected void finalize() throws java.lang.Throwable {
          super.finalize(); 
          System.out.println("Cake Object " + id + "is disposed");
           } 
           }

Running the above code, the following output:

$ javac FinalizationDemo.java 
$ java FinalizationDemoCake Object 1is createdCake Object 2is createdCake Object 3is createdCake Object 3is disposedCake Object 2is disposed
Published 58 original articles · won praise 6 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_43674360/article/details/104119359
Recommended