java方法methods
java中还是称之为“方法”好了。
In general, method declarations has six components :
包括这六部分:
- Modifier-(标识符): Defines access type of the method i.e. from where it can be accessed in your application. In Java, there 4 type of the access specifiers.
- public: accessible in all class in your application.
- protected: accessible within the class in which it is defined and in its subclass(es)
- private: accessible only within the class in which it is defined.
- default (declared/defined without using any modifier) : accessible
within same class and package within which its class is defined.
- The return type(返回值) : The data type of the value returned by the method or void if does not return a value.
- Method Name (方法名): the rules for field names apply to method names as well, but the convention is a little different.
- Parameter list (参数列表): Comma separated list of the input parameters are defined, preceded with their data type, within the
enclosed parenthesis. If there are no parameters, you must use empty
parentheses (). - Exception list (异常列表): The exceptions you expect by the method can throw, you can specify these exception(s).可以列出方法可能的异常会被引发,在此列表中可以指定这些异常。
- Method body : it is enclosed between braces. The code you need to be executed to perform your intended operations.
How to name a Method?
A method name is typically a single word that should be a verbin lowercase or multi-word, that begins with a verb in lowercase followed by adjective, noun….. After the first word, first letter of each word should be capitalized. For example, findSum, computeMax, setX and get.
方法的命名通常为动词(小写)后可跟一个名词(后面的单词首字母大写)。computeMax。
//自己写的
import java.util.Scanner;
class Addition{
int sum;
public int addTwoInt(int a,int b) {
sum = a + b;
return sum;
}
}
public class Main {
public static void main(String args[]){
Addition add = new Addition();
int s = add.addTwoInt(1,2);
System.out.print(s);
}
}
// 标准版本
//Program to illustrate methodsin java
import java.io.*;
class Addition {
int sum = 0;
public int addTwoInt(int a, int b){
// adding two integer value.
sum = a + b;
//returning summation of two values.
return sum;
}
}
class GFG {
public static void main (String[] args) {
// creating an instance of Addition class
Addition add = new Addition();
// calling addTwoInt() method to add two integer using instance created
// in above step.
int s = add.addTwoInt(1,2);
System.out.println("Sum of two integer values :"+ s);
}
}