21 面向对象编程 方法回顾和加深 代码:方法的定义 代码:方法的调用
方法回顾和加深
概念
- 方法的定义
- 修饰符
- 返回类型
- break(跳出switch,结束循环) 和 return (方法结束)的区别
- 方法名:注意规范(驼峰命名规则),见名知意
- 参数列表:(参数类型,参数名) …
- 异常抛出
- 方法的调用:递归
- 静态方法
- 非静态方法
- 形参和实参
- 值专递和引用传递
- this关键字:当前这个类,当前这个对象
代码:方法的定义
/*
修饰符 返回值类型 方法名(...){
// 方法体
return 返回值;
}
*/
// return 结束方法,返回一个结果
public String sayHello(){
return "hello,word";
}
public int max(int a,int b){
return a>b ? a :b;// 三元运算符:a大于b 显示a否则显示b
}
// 数组下标越界:Arrayindexoutofbounds
// 异常
public void readFile(String file) throws IOException(){
}
代码:方法的调用
// 静态方法 static:直接通过类型.方法名()调用
// 非静态方法:需要实例化类,new关键字
// 对象类型 对象名 = 对象值;
Studen student = new Student();
student.say();
// ============
// static是和类一起加载的
public static void a(){
}
// 类实例化(new)之后才存在
public void b(){
}
// ================
// main方法调用
// 实际参数和形式参数的类型要对应!
int add = Demo.add(10,20);
System.out.println(add);
// 形式参数a b
public static int add(int a,int b){
return a+b;
}
// ======================
// 值传递
// main方法
int a = 1;
System.out.println(a); // 1
Demo.change(a);
System.out.println(a); // 1
// 返回值为空
public static void change(int a){
a = 10;
}
// ========================
// 引用传递:独享,本质还是值传递
// main方法
Person person = new Person();
System.out.print(person.name); // null
demo.chage(person)
System.out.print(person.name); // chihiro
public static void change(Person person{
// person是一个对象:指向的 --> Person person = new Person();这是一个具体的人,可以改变属性!
person.name = "chihiro";
}
// 定一了一个Peseon类,有一个属性:name
class Person{
String name;
}
本文来自博客园,作者:千寻简,转载请注明原文链接:https://www.cnblogs.com/opxc/p/15970132.html