回顾方法及加法
方法的定义
-
修饰符
-
返回类型
//Dome01类
public class Dome01 {
//main方法
public static void main(String[] args) {
}
/*
修饰符 返回值 方法名(...){
//方法体
return 返回值;
}
*/
public String sayhello(){
return "hello,word!";
}
public int max(int a,int b){
//如果a>b则输出a,否则输出b
return a>b?a:b;//三元运算
}
}
-
break(:跳出switch,结束循环) 和return(:结束方法,返回一个结果!)的区别
-
方法名:注意规范,见名知意
-
参数列表:(参数类型,参数名)和(参数类型...参数名)
-
异常抛出:疑问
方法的调用
-
静态方法
-
非静态方法
//学生类
public class Student {
//静态方法 static
//非静态方法 不加static
//静态方法
public static void say(){
System.out.println("学生说话了");
}
//非静态方法
public void say1(){
System.out.println("学生说话了");
}
}
public class Dome02 {
public static void main(String[] args) {
//调用Student类中的静态 say方法
Student.say();
//调用Student类中的非静态 say1方法
//实例化这个类 new
new Student().say1();//写法 1
//写法 2
//对象类型 对象名 =对象值
Student student=new Student();
student.say1();
}
}
注意一下方式调用会报错
//和类一起加载的
public static void a(){
b();//报错,无法调用不存在的类
}
//类实例化 之后才存在
public void b(){
}
静态方法只能调用静态方法,非静态方法可以调用静态方法
-
形式参数和实际参数
public static void main(String[] args) {
//实际参数和形式参数的类型要对应!
add(5,9);//实际参数:给a和b赋值5和9
}
//设定形式参数 int a和int b
private static int add(int a,int b){
return a+b;
}
-
值传递和引用传递
//值传递 Java是指传递
public class Demo04 {
public static void main(String[] args) {
int a=1;
System.out.println(a);//输出:1
Demo04.charge(a);
System.out.println(a);//输出:1
}
//返回值为空
public static void charge(int a){
a=10;
}
//引用传递:传递对象 本质还是值传递
public class Demo05 {
public static void main(String[] args) {
Perosn perosn=new Perosn();
System.out.println(perosn.name);//输出默认值null
Demo05.change(perosn);
System.out.println(perosn.name);
}
public static void change(Perosn perosn){
//perosn是一个对象:指向的---> Perosn perosn=new Perosn();这是一个具体的人,可以改变属性
perosn.name="瓜皮";
}
}
//定义了一个perosn类,有一个属性:name
class Perosn{
String name;//默认值为null
}