Bootstrap

从入门到入土,java学习day6(面向对象和练习,今天练习偏复杂有些难度)

面向对象

拿需要的东西解决对应的问题

面向对象思维更符合符合人类思维习惯,因为举例来说,如果你要喝水你就会取用一个杯子来接水然后喝下去,你想某个人你就可以用手机联系她,所以这就是面向对象思维。

设计对象并使用

类和对象

类:是对象共同特征的描述

对象:是真实存在的具体东西

定义类

public class 类名{

成员变量;成员方法;构造器;代码块;内部类;

}

获得类的对象

类名 对象名 = new 类名();

使用对象

访问属性:对象名.成员变量

访问行为:对象名.方法名(...)

注意事项

用来描述一类事物的类,专业叫做Javabean类

是不写main方法的

之前编写main方法的类,叫做测试类

我们可以在测试类中创建javabean类的对象并进行赋值调用

类名首字母大写,驼峰命名

一个Java文件中可以定义多个class类,且只能是一个类是 public修饰,而且public修饰的类名必须成为代码文件名,实际开发中建议还是一个文件定义一个class类

成员变量的完整定义格式是:修饰符 数据类型 变量名称 = 初始化值

封装

告诉我们,如何正确设计对象的属性和方法

对象代表什么,就封装对应的数据,并提供数据对应的行为(会比较哲理)我举一个例子你就知道我为什么这么说,你关上门,好这是一个事件,那么门关上是应该封装到人还是门,很多人惯性思维觉得是人关上的门,其实不是。因为重点就是对应的对象,你要这么想,人只是给了门一个力,然后门关上的,所以应给封装到门。

可以让编程变得很简单,有什么事,找对象,调方法就行

降低我们的学习成本

修饰符

private 关键字

权限修饰符

可以修饰成员

被private修饰的成员只能在本类中才能访问

这样有利于保障安全性,外部就不会随意查看调取相关信息,也不会传一些不合法数据进来,主要靠get set方法

this关键字

局部变量:定义在方法中的变量

成员变量:定义在方法外面,类中是

就近原则,调用最近的,如果加上了this就指的是方法调用者的地址,所以可以用来区别

this用来区别成员变量和局部变量

构造方法

构造方法也叫作构造器,构造函数

作用:在创建对象的时候给成员变量进行赋值

这里注意不能将构造方法和创建变量等同,他只是其中的一步,初始化

格式

public class Student{

修饰符 类名(参数){

方法体;

}

}

特点

1.方法名与类名相同,大小写也要一致

2.没有返回值类型,连void都没有

3.没有具体的返回值(不能由return带回结果数据)

执行时机

1.创建对象的时候由虚拟机调用,不能手动调用构造方法

2.每创建一次对象,就会调用一次构造方法

构造方法注意事项

构造方法的定义

如果没有定义构造方法,系统将给出一个默认的无参数构造方法

如果定义了构造方法,系统将不再提供默认的构造方法

构造方法的重载

带参构造方法,和无参数构造方法,两者方法名相同,但是参数不同,这叫做构造方法的重载

推荐的使用方式

无论是否使用,都手动书写无参数构造方法,和带全部参数的构造方法

JavaBean

标准的JavaBean类

类名需要见名矩意

成员变量使用private修饰

提供至少两个构造方法

无参构造方法

带全部参数的构造方法

成员方法

提供每一个成员变量对应的setXxx()/getXxx()

如果还有其他行为,也需要写上

快捷键:alt+ins会出现要生成的选项,进行选择即可    PTG插件可以下载右键代码空白就可以生成标准javabean类

对象内存图

java内存分配(下面几部分之前讲过)

方法区

本地方法栈

寄存器

注意:从JDK8开始,取消方法区,新增元空间,把原来方法区的功能进行拆分,有的功能放到堆中有的功能放到了元空间。

一个对象的内存图

Student s = new Student();

1.加载class文件

2.申明局部变量

3.在堆内存中开辟一个空间

4.默认初始化

5.显示初始化

6.构造方法初始化

7.将堆内存中的地址值给左边的局部变量

两个对象,就是重复一遍,且不用再加载一次.class字节码文件

两个引用指向同一个对象

只要理解了地址,就好理解,就是第二个赋值也是第一个的地址值,然后第二块就会把第一块给覆盖。

基本数据类型,引用数据类型

基本数据类型,数据值存储在自己的空间中,赋值给其他变量,也是赋的真实值

引用数据类型,数据值是存储在其他空间中,自己空间中存储的是地址值,赋值给其他变量,赋的地址值

this的内存原理

this的本质:代表方法调用者的地址值

所以this所指的变量,可以区别

训练

1.文字版格斗游戏,每个游戏角色的姓名,血量,都不相同,在选定人物时,这些信息就应该被确定下来

首先定义角色类,生成标准javabean类

package mianxiang;
import java.util.Random;
public class Role {
    private double blood;
    private String name;

    public Role() {
    }

    public Role(double blood, String name) {
        this.blood = blood;
        this.name = name;
    }

    /**
     * 获取
     * @return blood
     */
    public double getBlood() {
        return blood;
    }

    /**
     * 设置
     * @param blood
     */
    public void setBlood(double blood) {
        this.blood = blood;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    public void attack(Role role) {
        Random r= new Random();
        int hurt = r.nextInt(20)+1;
        int remainingBlood = (int) (role.getBlood() - hurt);
        remainingBlood = remainingBlood < 0 ? 0 : remainingBlood;
        role.setBlood(remainingBlood);
        System.out.println(this.getName() + "攻击了" + role.getName() + ",造成了" + hurt + "点伤害," + role.getName() + "还剩下" + remainingBlood + "点血");
    }
}

然后是测试类

package mianxiang;

public class GameTest {
    public static void main(String[] args) {
        Role role1 = new Role(100, "盖伦");
        Role role2 = new Role(100, "提莫");
        while (true) {
            role1.attack(role2);
            if (role2.getBlood() == 0) {
                System.out.println(role2.getName() + "死了" + role1.getName() + "赢了");
                break;
            }
            role2.attack(role1);
            if (role1.getBlood() == 0) {
                System.out.println(role1.getName() + "死了" + role2.getName() + "赢了");
                break;
            }
        }
    }
}

2.定义数组存储三个商品对象。商品属性:ID,名字,价格,库存,创建三个商品对象然后存储到数组中

package mianxiang;

public class Goods {
    private String name;
    private double price;
    private int id;
    private int count;

    public Goods(String name, double price, int id, int count) {
        this.name = name;
        this.price = price;
        this.id = id;
        this.count = count;
    }

    public Goods() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

测试类

package mianxiang;

public class TestGoods {
    public static void main(String[] args) {
        Goods g1 = new Goods("笔记本", 1000, 1, 10);
        Goods g2 = new Goods("手机", 500, 2, 20);
        Goods g3 = new Goods("平板", 800, 3, 30);
        Goods[] arr = new Goods[3];
        arr[0] = g1;
        arr[1] = g2;
        arr[2] = g3;
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i].getName() + "," + arr[i].getPrice() + "," + arr[i].getId() + "," + arr[i].getCount());
        }
    }
}

3.定义数组存储3部汽车对象。汽车的属性:品牌,价格,颜色。创建三个汽车对象,数据通过键盘录入而来,并把数据存入到数组当中。

键盘录入问题

nextInt();接收整数

nextDouble();接收小数

next();接受字符串

遇到空格,制表符,回车就停止接受。这些符号后面的数据就不会接受了

nextLine(); 接收字符串

可以接收空格,制表符,遇到回车才停止接收数据

package mianxiang;

public class Car {
    private String brand;
    private String color;
    private double price;

    public Car() {
    }

    public Car(String brand, String color, double price) {
        this.brand = brand;
        this.color = color;
        this.price = price;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

测试类

package mianxiang;
import  java.util.Scanner;

public class TestCar {
    public static void main(String[] args) {
        Car[] arr = new Car[3];
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 3; i++) {
            Car c = new Car();
            System.out.println("请输入第" + (i + 1) + "辆车的品牌、颜色和价格:");
            String brand = sc.next();
            String color = sc.next();
            double price = sc.nextDouble();
            c.setBrand(brand);
            c.setColor(color);
            c.setPrice(price);
            arr[i] = c;
        }
        for (int i = 0; i < 3; i++) {
            System.out.println("第" + (i + 1) + "辆车的品牌、颜色和价格分别为:" + arr[i].getBrand() + " " + arr[i].getColor() + " " + arr[i].getPrice());
        }

    }
}

4.定义一个长为3的数组,数组存储1~3名学生对象作为初始数据,学生对象的学号,姓名各不相同。

学生的属性:学号,姓名,年龄。

要求1:再次添加一个学生对象,并在添加的时候进行学好的唯一性判断

要求2;添加完毕之后,遍历所有学生信息。

要求3:通过id删除学生信息,如果存在,则删除,如果不存在,则提示删除失败

要求4:删除完毕之后,遍历所有学生信息

要求5:查询数组id为“002”的学生,如果存在,则将他的年龄+1岁

package mianxiang;

public class Student {
    private int id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return id
     */
    public int getId() {
        return id;
    }

    /**
     * 设置
     * @param id
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

}

测试类

package mianxiang;

public class TestStudent {
    public static void main(String[] args) {
        // 定义一个长度为 3 的数组,存储学生对象
        Student[] students = new Student[3];
        students[0] = new Student(1, "张三", 20);
        students[1] = new Student(2, "李四", 21);
        students[2] = new Student(3, "王五", 22);

        // 要求 1:添加一个新的学生对象,并进行学号的唯一性判断
        Student newStudent = new Student(4, "赵六", 23);
        boolean isIdUnique = true;
        for (Student student : students) {
            if (student != null && student.getId() == newStudent.getId()) {
                isIdUnique = false;
                break;
            }
        }
        if (isIdUnique) {
            // 扩展数组长度
            Student[] newStudents = new Student[students.length + 1];
            System.arraycopy(students, 0, newStudents, 0, students.length);
            newStudents[newStudents.length - 1] = newStudent;
            students = newStudents;
            System.out.println("学生添加成功!");
        } else {
            System.out.println("该学号已存在,添加失败!");
        }

        // 要求 2:遍历所有学生信息
        System.out.println("添加学生后,所有学生信息如下:");
        for (Student student : students) {
            if (student != null) {
                System.out.println(student);
            }
        }

        // 要求 3:通过 id 删除学生信息
        int deleteId = 3;
        boolean isDeleted = false;
        int index = -1;
        for (int i = 0; i < students.length; i++) {
            if (students[i] != null && students[i].getId() == deleteId) {
                index = i;
                isDeleted = true;
                break;
            }
        }
        if (isDeleted) {
            // 移动元素覆盖要删除的元素
            for (int i = index; i < students.length - 1; i++) {
                students[i] = students[i + 1];
            }
            // 创建新数组,长度减 1
            Student[] newStudents = new Student[students.length - 1];
            System.arraycopy(students, 0, newStudents, 0, newStudents.length);
            students = newStudents;
            System.out.println("学号为 " + deleteId + " 的学生删除成功!");
        } else {
            System.out.println("删除失败,未找到学号为 " + deleteId + " 的学生。");
        }

        // 要求 4:删除完毕之后,遍历所有学生信息
        System.out.println("删除学生后,所有学生信息如下:");
        for (Student student : students) {
            if (student != null) {
                System.out.println(student);
            }
        }

        // 要求 5:查询数组 id 为 “2” 的学生,如果存在,则将他的年龄 +1 岁
        int targetId = 2;
        for (Student student : students) {
            if (student != null && student.getId() == targetId) {
                student.setAge(student.getAge() + 1);
                System.out.println("学号为 " + targetId + " 的学生年龄已更新为 " + student.getAge() + " 岁。");
                break;
            }
        }

        // 再次遍历所有学生信息,查看更新后的结果
        System.out.println("更新年龄后,所有学生信息如下:");
        for (Student student : students) {
            if (student != null) {
                System.out.println(student);
            }
        }
    }
}

;