目录
一、类和对象的概念
对象:现实世界中客观存在的物体都是对象,具有属性和方法,其中属性描述对象的特征,方法描述对象的行为
类:具有相同属性和方法的多个对象的集合
类是对对象的抽象,对象是类的具体
类是创建对象的模板
二、方法
方法的定义语法:
访问权限修饰符 返回值类型 方法名(数据类型 变量名1,数据类型 变量名2,...,数据类型 变量名n){方法体}
1)访问权限修饰符有4种:public(公共的) protected(受保护的) 默认的(不写修饰符) private(私有的)
2)返回值类型:
没有返回值的时候,写void
有返回值,返回值可以是基本数据类型,也可以是引用数据类型
3)方法名:
采用小驼峰命名法
见名知意
4)方法的参数列表,可以有可以没有,有参数的时候,可以有一个,也可以有多个
5)方法体:方法能具体干什么事情的代码
方法根据是否有返回值和参数分类:
1)无返回值的无参方法
2)无返回值的有参方法
3)有返回值的无参方法
4)有返回值的有参方法
调用有返回值的方法注意事项:
调用一个有返回值的方法,对于返回的结果,你可以直接输出,也可以使用返回类型的变量去接收返回值
调用需要传递参数的有参方法注意事项:
方法需要多少个参数,你就要传递多少个参数,并且需要按照其定义的顺序传递参数
综上所述,调用方法的两个原则是:
1)给什么接什么---》返回什么结果给你,你就用什么变量接收
2)要什么给什么---》方法需要什么参数,你就给什么参数
方法在传参时还需要注意:基本数据类型,操作传递的是变量的值,改变一个变量的值不会影响另一个变量的值。引用数据类型(类、数组和接口),赋值是把原对象的引用(可理解为内存地址)传递给另一个引用
应用:使用学员对象数组作为参数,实现学员成绩修改 如果学员成绩小于60,集体提高2分
编写方法类:
public class Student {
String name;
double score;
public static void addScore(Student students[]){
for(int i = 0;i<students.length;i++){
if(students[i].score<60){
for(int j = 0;j<students.length;j++){
students[j].score += 2;
}
break;
}
}
}
}
编写测试类:
public class StudentTest {
public static void main(String[] args) {
Student stu1 = new Student();
stu1.name = "张三";
stu1.score = 80;
Student stu2 = new Student();
stu2.name = "李四";
stu2.score = 90;
Student stu3 = new Student();
stu3.name = "王五";
stu3.score = 50;
Student stu4 = new Student();
stu4.name = "赵六";
stu4.score = 60;
Student stu5 = new Student();
stu5.name = "孙七";
stu5.score = 70;
Student stus[] = {stu1,stu2,stu3,stu4,stu5};
Student.addScore(stus);
for(int i = 0;i< stus.length;i++){
System.out.println(stus[i].name+":"+stus[i].score);
}
}
}