方法的定义
-
方法类似于其他语言的函数,用来完成特定功能的代码片段
-
方法包括一个方法头和一个方法体
-
修饰符 返回值类型 方法名(参数类型 参数名)
{
…
方法体
…
return 返回值
}
public static int min(int num1,int num2){
int min;
if(num1==num2){
System.out.println("两个数相等");
} if (num1>num2){
min=num2;
}else{
min=num1;
}
return min;
}
调用
-
调用方法的方式一般有两种 根据有无返回值来选择
如果方法是有返回值的时候 ,方法调用通常被当作一个值
public static void main(String[] args) {
//调用方法
System.out.println(min(10,20));
}
没有返回值的是void 方法调用一定是一条语句
Systemm.out.println("hello world");
-
还有一种调用方法 对象名.方法名(实参列表)
在一个类中调用另一个类的方法 有两种方法
当被调用的方法是
静态方法(static)
用 类名.方法名
当被调用的方法是
非静态方法
实例化方法所在的这个类 new
对象类型 对象名 = new 对象值;
然后通过对象名.方法名();
public class demo01 {
public static void main(String[] args) {
//直接通过类名进行调用
Student.print();
//通过实例化进行调用
Student student=new Student();
student.say();
}
}
public class Student {
//静态方法
public static void print(){
System.out.println("静态类");
}
//非静态方法
public void say(){
System.out.println("非静态");
}
}
在同一个类中进行调用也是一个道理
public class demo01 {
public static void main(String[] args) {
rint();
demo01 d=new demo01();
d.sa();
}
public static void rint(){
System.out.println("静类");
}
public void sa(){
System.out.println("非态");
}
}