package day03;
/*
面向过程:
最小的处理单位是函数。把大问题分解成小问题,每个问题一个函数来解决
面向对象:
最小小处理单位是类。把大象装入冰箱,这个过程有哪些事物,每个事物的行为。
1.冰箱:开关门
2.大象:进入(冰箱)
3.人:打开关闭(冰箱)、操作(大象)
属性:成员变量
行为:方法
*/
public class Demo01 {
public static void main(String[] args) {
// 具体的学生,对象、实例
Student zhangsan = new Student();
zhangsan.name = "张三"; // 调用属性,设置或获取属性的值
zhangsan.gender = '男';
zhangsan.age = 22;
zhangsan.weight = 75;
zhangsan.height = 170;
zhangsan.sleeping(); // 调用无参的方法
zhangsan.learning("图书馆", "三国演义"); // 调用有参的方法
zhangsan.info();
Student lisi = new Student();
lisi.name = "李四";
lisi.age = 25;
lisi.gender = '男';
lisi.weight = 80;
lisi.height = 190;
lisi.learning("宿舍", "java");// 没有返回值的方法,默认返回是null
lisi.info();
int aa = lisi.getAge(); // 有返回值的方法,用变量接受这个返回值
System.out.println("年龄:" + aa);
}
}
// 类型:相同特征的一个群体。
class Student {
// 成员变量:在类中定义的变量,属于实例,通过new创建实例时,这些属性就创建了。实例销毁时,这些实例才会释放。
// 堆内存(更新慢) public/private、static、final可以用来修饰成员变量
// 局部变量:在方法中定义的变量,或者方法的参数。调用方法时才会创建局部变量,方法调用完释放。
// 栈内存(更新快)final可以用来修饰局部变量
// 成员变量和局部变量的名字可以一样,成员变量前加this来标识
String name;
char gender;
int age;
float height;
float weight;
public void setName(String name) {
// this.name 这是成员变量
// = 后面的 name 是局部变量
this.name = name;
}
public void info() {
System.out.println("姓名:" + name + ",性别:" + gender + ",年龄:" + age + ",身高:" + height + ",体重:" + weight);
}
// public 表示公共的
// void 表示没有返回值
// ()里面没有内容,表示没有参数
public void sleeping() {
System.out.println(name + "正在睡觉");
}
// 方法带了两个String类型的参数,一个表示地点,一个表示书
public void learning(String place, String book) {
System.out.println(name + "在" + place + "看" + book);
}
// 方法声明返回一个int类型的值,方法体中用return返回对应类型的值
public int getAge() {
return age;
}
}
/*
对象数组、对象参数、可变参数
*/
import java.util.Arrays;
public class Demo06 {
public static void main(String[] args) {
// 新建三个学生,把学生加入数组
Students s1 = new Students("Lily", 80);
Students s2 = new Students("Lucy", 40);
Students s3 = new Students("Tony", 55);
Students[] ss = {s1, s2, s3};
System.out.println(Arrays.toString(ss));
// 调用静态方法 Demo06.modifyScore 类名.方法名,同一个类中类名可省略
modifyScore(ss);
System.out.println(Arrays.toString(ss));
Students s4 = new Students("Jack", 50);
System.out.println(s4);
modifyScore(s4);
System.out.println(s4);
Students s5 = new Students("Jack1", 40);
Students s6 = new Students("Jack2", 55);
modifyScore1(s5,s6);
System.out.println(s5);
System.out.println(s6);
}
// 修改学生的分数,如果小于60,将分数改为60
public static void modifyScore(Students stu) {
if (stu.score < 60) {
stu.score = 60;
}
}
// 批量修改学生分数
public static void modifyScore(Students[] stu) {
for (Students s : stu) {
if (s.score < 60) {
s.score = 60;
}
}
}
// 可变参数,当做一个数组来看,可以传入n个学生
public static void modifyScore1(Students ...stu) {
for (Students s : stu) {
if (s.score < 60) {
s.score = 60;
}
}
}
}
class Students {
String name;
float score;
public Students(String name, float score) {
this.name = name;
this.score = score;
}
@Override
public String toString() {
return "Students{" +
"name='" + name + '\'' +
", score=" + score +
'}';
}
}
|