import java.io.IOException;
public class Demo01 {
//修饰符 返回值类型 方法名(...){}
public static int add(int a, int b) {
return a + b;
}
//修饰符 void 方法名
public void say() {
//方法体
return;//返回空
}
//三元运算符
public int max(int a, int b) {
return a > b ? a : b;
}
//完整的方法还包括异常的抛出
public void readFile(String file) throws IOException {
}
}
方法的调用
实例
public class Demo02 {
public static void main(String[] args) {
//类的静态方法的调用
Student.say();
//类的非静态方法的调用
//实例化这个类
Student student = new Student();
student.study();
}
}
public class Student {
String name;
int age;
public static void say() {
System.out.println("学生说话");
}
public void study() {
System.out.println("学生学习");
}
}
//方法之间的调用
//静态方法随着类创建;非静态方法随着对象实例化创建
public class Demo03 {
public static void main(String[] args){
}
//静态方法
public static void a(){
b();//调用静态方法
//c();静态方法不能调用非静态方法
}
public static void b(){
}
//非静态方法
public void c(){
d();
a();//非静态方法可以调用静态方法
}
public void d(){
}
}
//形参与实参
public class Demo04 {
public static void main(String[] args) {
//实际参数和形式参数的数据类型必须一致
int add = add(10, 20);
System.out.println(add);
}
public static int add(int a, int b) {
return a + b;
}
}
//值传递
public class Demo05 {
public static void main(String[] args) {
int a = 20;
System.out.println("进入方法前a=" + a);
change(a);//把a的值拷贝给形式参数
System.out.println("进入方法后a=" + a);
}
//方法没有返回值
public static void change(int a) {
a = 10;
}
}
//引用传递
public class Demo06 {
public static void main(String[] args) {
Person person = new Person();
//首先输出一下当前的name的值
System.out.println("name的初始值为:" + person.name);
//调用方法change 把对象person传进去
change(person);
//看一看经过方法处理的name的值是多少
System.out.println("name现在的值为:" + person.name);
}
//定义一个方法用于改变name的值
//参数列表:参数类型 参数名 Person person
public static void change(Person person) {
person.name = "qinjiang";
}
}
//一个类中只能有一个public修饰的类
class Person {
String name;
}