静态方法: 有 static 修饰就是静态方法
可以通过类名调用:
类名.方法名(para);
如果在同一个类中可以直接调用
声明静态方法格式:
static 返回值类型 方法名(方法参数) {
方法体
}
public class MainTest {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入3个整数");
int num1 = s.nextInt();
int num2 = s.nextInt();
int num3 = s.nextInt();
int b = add(num1,num2);
System.out.println("前两个数之和为:"+b);
}
static int add(int num1,int num2) {
int a = num1+num2;
return a;
}
}
实例方法 :没有static 修饰的就是实例方法
通过实例调用 (对象调用) 对象名.方法名(para)
对象需要创建
类名 自己起名字 = new 类名(); //创建对象
声明实例方法:
返回值类型 方法名(方法参数){
方法体
}
public class MainTest {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入3个整数");
int num1 = s.nextInt();
int num2 = s.nextInt();
int num3 = s.nextInt();
MainTest MainTest = new MainTest ();
int b = MainTest.add(num1,num2);
System.out.println("前两个数之和为:"+b);
}
int add(int num1,int num2) {
int a = num1+num2;
return a;
}
方法调用的语法:
静态方法: 类名.方法名(实参);
实例方法: 对象名.方法名(实参);
补充:方法调用时 传参 要注意 实参 的 个数 顺序 类型 要和 形参一致
- 如果 需要 使用方法的返回值 可以定义一个 对应类型的变量 来接收 方法调 * 用的 返回值 : int result = methodDemo1.add(3, 2);
- 在一个类中 声明的方法 无论是 静态方法 还是 实例方法 他们之间 是 平级的 * 不要相互嵌套 ,就是不要在 一个方法中 去 声明 另一个方法 可以在 一个方法中 调用 另一个方法