先贴出一段代码复习方法
定义一方法,用于求2个数中的较大数,并将其返回,这2个数字在主方法中由用户输入
public class Math {
static void Max(int a, int b) { //方法中传入两个参数
if(a>b) //比较a与b 的大小
System.out.println(a); //a大于b输出a
else System.out.println(b); //b大于a输出b
}
}
给大家说明一下这里可以就在Math类中写一个主方法来测试但是为了保证Math方法类的纯净性,还是建议另外写一个测试类
不要这样写
public class Zuoye3 {
static void Max(int a, int b) {
if(a>b)
System.out.println(a);
else System.out.println(b);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
Zuoye3.Max(a,b);
}
}
另写一个类不费事的
正确写法
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt(); //用a,b分别来接收两个数字
int b=sc.nextInt();
Zuoye3.Max(a,b); //用类名.方法名来调用方法
}
}
这里有人就有疑问,有的方法他不能用类名来调用那是怎么回事呢???
方法的调用
方法分为静态方法跟实例方法两种
静态方法用static(词义静态)来修饰 就像
public static void main(String[] args)
static void Max(int a, int b)
实例方法呢就像
void Max(int a, int b)
他少了一个 static那么他们有什么区别呢
相比大家可以找到有啥不同吧,也就是说静态方法可以直接通过类名.方法名来调用
那实例方法呢
实例方法只能通过创建对象来调用
方法中调用其他方法
在静态方法中 调用实例方法 对象.方法名
在静态方法中 调用静态方法 类名.方法名
在实例方法中 调用实例方法 对象.方法名
在实例方法中 调用实例方法 类名.方法名
下篇跟大家一起看看一道综合题