开发Java后端Java - 类和对象
MelodyJava 类和对象
1.1 类和对象
类: 是对象共同特征的描述;
对象: 是真实存在的具体东西。
在Java中,必须设计类才能获取对象。
1.1.1 如何定义类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class phone { String brand; double price; public void call(){ System.out.println("打电话"); } public void playgame(){ System.out.println("玩游戏"); } }
|
定义类的补充注意事项
- 类名首字母建议大写,需要见名知意,驼峰模式。
- 一个
Java
文件中可以定义多个class
类,且只能一个类是public
修饰,而且public
修饰的类名必须成为代码文件名
实际开发中建议还是一个文件定义一个class类
- 成员变量的完整定义格式是:
修饰符 数据类型 变量名称 = 初始化值;
一半无需指定初始化直,存在默认值。
1.1.2 如何调用类
1 2 3 4 5 6 7 8 9 10 11 12
| public class phoneTest{ public static void main(String[] args){ phone p = new Phone(); p.brand = "小米"; p.price = 1999.9; p.call(); p.playgame(); } }
|
1.1.3 this
this的内存原理
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Student { private int age; private StRING NAME;
public void method() { int age = 10; System.out.println(age); System.out.println(this.age); }
public void setName(String name) { this.name = name; } }
|
1 2 3 4 5 6
| public class StudentTest { public static void main(String[] args) { Student s = new Student(); s.method(); } }
|
this
的作用: 区分局部变量
和成员变量
this
的本质: 所在方法调用者的地址值

1 2 3 4 5 6 7 8
| public class StudentDemo { public static void main(String[] args) { Student s1 = new Student(); s1.setName("竹小玲"); Student s2 = new Student(); s1.setName("桥小久"); } }
|
1.1.4 构造方法
构造方法
也叫构造器
、构造函数
作用: 在创建对象
的时候给成员变量
进行初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class person { private String name; private Integer age;
public person() { System.out.println("默认的无参构造函数"); }
public person(String name, Integer age) { this.name = name; this.age = age; }
public Integer getAge() { return age; }
public String getName() { return name; } }
public class run { public static void main(String[] args) { person p = new person("张三", 15); System.out.println(p.getName()); System.out.println(p.getAge()); 15 } }
|
构造器的注意事项
类
在设计时,如果不写构造器
,Java
会自动为类
生成一个无参构造器
- 一旦定义了
有参构造器
,Java
就不会自动生成无参构造器
了,此时需要写一个无参构造器
带参构造
和无参构造
方法,两者方法相同,但参数
不同,构成了构造方法
的重载
构造器小结
创建对象的时候,由虚拟机自动调用,给成员变量初始化使用
- 无参数构造方法: 初始化对象时,成员变量均采用默认值
- 有参数构造方法: 初始化对象时,同时可以给对象赋值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public class person { private String name; private Integer age;
public person(String name, Integer age) { this.name = name; this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; } }
public class method01 { public static void main(String[] args) { person p = new person(); p.setAge(17); p.setName("张三"); System.out.println(p.getName()); System.out.println(p.getAge()); } }
|
1.1.5 对象内存图
- 对于多个对象在内存中存储的原理

在上述图中,首先Test.class
会被加载到方法区中,此时main
方法会进入栈内存中,main
方法创建了一个Student
对象,此时Student.class
会加载到方法区
,并且在堆内存
中会开辟一个空间用来存储Student
类的成员变量
和成员方法
,并且将地址
赋值给s1
变量,通过s1
变量中
所存储的地址
来对堆内存
中存储的成员变量
进行赋值
,并且调用其成员方法
进行输出
这次在创建第二个Student
对象时,因为方法区已经存在Student.class
字节码文件,所以不会再重新去加载,并且直接会在堆内存
中开辟一个空间来存储
Student
对象并且会分配一个地址
给s2
来指向堆内存
中的空间
1.1.6 基本数据类型和引用数据类型
基本数据类型
:数据值是存储到自己的空间中
特点:赋值给其他变量,也是赋的真实的值
引用数据类型
:数据值是存储在其他空间中,自己空间中存储的是地址值
特点: 复制给其他变量时,赋值的是地址值
1.2 封装
对象
代表什么,就得封装对应的数据,并提供数据对应的行为
用类设计对象
处理某一个事物的数据
时,应该把要处理的数据
,以及处理这些数据的方法
,设计到一个对象
中去
封装
的设计规范
合理隐藏,合理暴露
公开成员
,使用public
(公开)进行修饰
隐藏成员
,使用private
(隐藏、私有)进行修饰
1.3 权限修饰符
1.3.1 private
private
关键字是一个权限修饰符
- 可以修饰
成员
(成员变量
和成员方法
)
- 被
private
修饰的关键字只能在本类中才能访问
- 针对
private
修饰的成员变量,如果需要被别的类中使用需要提供相应的方法
- 提供
setXXX(参数)
方法,用于给成员变量
赋值,方法应使用public
修饰
- 提供
getXXX(参数)
方法,用于获取成员变量
的值,方法应使用public
修饰
1.4 JavaBean
- 类名需要
见名知意
- 成员变量使用
private
修饰
- 至少提供两个
构造方法
- 成员方法
- 提供每一个
成员变量
对应的setXXX()/getXXX()
- 如果还有其他
行为
,也需要写上
1.5 面向对象综合练习
1.5.1 文字版格斗游戏
案例描述:格斗游戏,每个游戏角色的姓名,血量,都不相同,在选定人物时(new这些对象时),这些信息就应该被确认下来
// 第一版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| public class Role { private String name; private Integer blood;
public Role() { }
public Role(String name, Integer blood) { this.name = name; this.blood = blood; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getBlood() { return blood; }
public void setBlood(Integer blood) { this.blood = blood; }
public void attack(Role role) { int damage = new Random().nextInt(20) + 1; int remainBlood = role.getBlood() - damage; remainBlood = remainBlood > 0 ? remainBlood : 0; role.setBlood(remainBlood); System.out.println(this.getName() + "攻击了" + role.getName() + "一下" + ",造成了" + damage + "点伤害," + role.name + "还剩余" + role.getBlood() + "血量"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class GameRun { public static void main(String[] args) { Role s1 = new Role("关羽",100); Role s2 = new Role("马超",100); while(true){ s1.attack(s2); if(s2.getBlood() == 0){ System.out.println(s2.getName() + "被KO了"); break; } s2.attack(s1); if(s1.getBlood() == 0){ System.out.println(s1.getName() + "被KO了"); break; } } } }
|
第二版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
| public class Role { private String name; private Integer blood; private char gender; private String face; String[] boyFaces = {"风流俊雅", "气宇轩昂", "相貌英俊", "五官端正"}; String[] girlFaces = {"美轮美奂", "沉鱼落雁", "亭亭玉立", "身材姣好"};
String[] attacksDesc = { "%s使出了一招[背心钉],转到对方的身后,一掌向%s背心的灵台穴拍去", "%s使出了一招[游空探爪],飞起身形自半空中变掌为抓锁向%s", "%s大喝一声,身形下伏,一招[劈雷坠地],排向%s双腿", "%s运气于掌,一瞬间掌心变得血红,一式[掌心雷],推向%s", "%s阴手翻起阳手跟进,一招[没遮拦],结结实实的捶向%s", "%s上步抢身,招中套招,一招[劈挂连环],连环攻向%s" }; String[] injuredDesc = { "结果%s退了半步,毫发无损", "结果给%s造成一处瘀伤", "结果一击命中,%s痛得弯下腰", "结果%s痛苦地闷哼了一声,显然受了点内伤", "结果%s摇摇晃晃,一跤摔倒在地", "结果%s脸色一下变得惨白,连退了好几步", "结果[轰]的一声,%s口中鲜血狂喷而出", "结果%s一声惨叫,像滩软泥般塌了下去" };
public Role() { }
public Role(String name, Integer blood, char gender) { this.name = name; this.blood = blood; this.gender = gender; setFace(gender); }
public char getGender() { return gender; }
public void setGender(char gender) { this.gender = gender; }
public String getFace() { return face; }
public void setFace(char gender) { Random r = new Random(); if (this.gender == '男') { int index = r.nextInt(boyFaces.length); this.face = boyFaces[index]; } else if (this.gender == '女') { int index = r.nextInt(girlFaces.length); this.face = girlFaces[index]; } else { this.face = "娇小可爱"; } }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getBlood() { return blood; }
public void setBlood(Integer blood) { this.blood = blood; }
public void attack(Role role) { Random r = new Random(); int index = r.nextInt(attacksDesc.length); String moves = attacksDesc[index]; System.out.printf(moves, this.getName(), role.getName()); System.out.println(); int damage = r.nextInt(20) + 1; int remainBlood = role.getBlood() - damage; remainBlood = remainBlood > 0 ? remainBlood : 0; role.setBlood(remainBlood); switch (remainBlood / 10) { case 9: System.out.printf(injuredDesc[0], role.getName()); break; case 8: System.out.printf(injuredDesc[1], role.getName()); break; case 7: System.out.printf(injuredDesc[2], role.getName()); break; case 6: System.out.printf(injuredDesc[3], role.getName()); break; case 5: case 4: System.out.printf(injuredDesc[4], role.getName()); break; case 3: case 2: System.out.printf(injuredDesc[5], role.getName()); break; case 1: default: System.out.printf(injuredDesc[6], role.getName()); break; } }
public void showRoleInfo() { System.out.println("姓名为" + getName()); System.out.println("血量为" + getBlood()); System.out.println("性别为" + getGender()); System.out.println("长相为" + getFace()); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public class GameRun { public static void main(String[] args) { Role s1 = new Role("银狼", 100, '女'); Role s2 = new Role("黑塔", 100, '女'); while (true) { s1.attack(s2); System.out.println(); if (s2.getBlood() == 0) { System.out.println(); System.out.println(s2.getName() + "被KO了"); break; } s2.attack(s1); if (s1.getBlood() == 0) { System.out.println(); System.out.println(s1.getName() + "被KO了"); break; } } } }
|
1.5.2 对象数组
案例描述: 定义数组存储3个汽车对象,汽车的属性:品牌、价格、颜色,创建三个汽车对象,数据通过键盘录入,并把对象存入到数组当中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| public class Car { private String brand; private Integer price; private String color;
public Car() { }
public Car(String brand, Integer price, String color) { this.brand = brand; this.price = price; this.color = color; }
public String getBrand() { return brand; }
public void setBrand(String brand) { this.brand = brand; }
public double getPrice() { return price; }
public void setPrice(Integer price) { this.price = price; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
@Override public String toString() { return "Car{" + "brand='" + brand + '\'' + ", price=" + price + ", color='" + color + '\'' + '}'; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class CarsTest { public static void main(String[] args) { Car[] arr = new Car[3]; Scanner sc = new Scanner(System.in); for (int i = 0; i < arr.length; i++) { Car c = new Car(); System.out.println("请输入品牌名字:"); String brand = sc.next(); c.setBrand(brand); System.out.println("请输入商品价格"); int price = sc.nextInt(); c.setPrice(price); System.out.println("请输入商品颜色"); String color = sc.next(); c.setColor(color); arr[i] = c; } for (int i = 0; i < arr.length; i++) { Car car = arr[i]; System.out.println(car.getBrand() + " " + car.getPrice() + " " + car.getColor()); } } }
|
案例描述: 定义数组存储3个手机对象,手机的属性:品牌、价格、颜色,要求,计算出三部手机的平均价格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public class Phone { private String brand; private double price; private String color;
public Phone() { }
public Phone(String brand, double price, String color) { this.brand = brand; this.price = price; this.color = color; }
public String getBrand() { return brand; }
public void setBrand(String brand) { this.brand = brand; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class PhoneTest { public static void main(String[] args) { Phone[] arr = new Phone[3]; Phone p1 = new Phone("小米", 3000.0, "白色"); Phone p2 = new Phone("华为", 2999.9, "黑色"); Phone p3 = new Phone("苹果", 5999.9, "红色"); arr[0] = p1; arr[1] = p2; arr[2] = p3; double sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i].getPrice(); } int avg = (int) sum / arr.length; System.out.println(avg); } }
|
案例描述: 定义数组存储4个女朋友对象,女朋友的属性:姓名、年龄、性别、爱好,统计年龄比平均值低的女朋友有几个?并把她们对应的所有信息打印出来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| public class girlFriend { private String name; private Integer age; private char gender; private String hobby;
public girlFriend() { }
public girlFriend(String name, Integer age, char gender, String hobby) { this.name = name; this.age = age; this.gender = gender; this.hobby = hobby; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public char getGender() { return gender; }
public void setGender(char gender) { this.gender = gender; }
public String getHobby() { return hobby; }
public void setHobby(String hobby) { this.hobby = hobby; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public class GirlFriendsTest { public static void main(String[] args) {
girlFriend[] arr = new girlFriend[4];
girlFriend g1 = new girlFriend("银狼", 18, '女', "打游戏"); girlFriend g2 = new girlFriend("黑塔", 18, '女', "研究"); girlFriend g3 = new girlFriend("克拉拉", 18, '女', "修机器"); girlFriend g4 = new girlFriend("阮梅", 22, '女', "研究");
arr[0] = g1; arr[1] = g2; arr[2] = g3; arr[3] = g4;
int sum = 0;
for (int i = 0; i < arr.length; i++) { sum += arr[i].getAge(); }
int avgAge = sum / arr.length; int count = 0;
for (int i = 0; i < arr.length; i++) { if (arr[i].getAge() < avgAge) { count++; System.out.println(arr[i].getName() + " " + arr[i].getGender() + " " + arr[i].getAge() + " " + arr[i].getHobby()); } } System.out.println("比平均年龄小的有" + count + "个");
} }
|
案例描述: 定义一个长度为3的数组,数组存储1~3的名学生对象作为初始数据,学生对象的学号,姓名各不相同。学生的属性
:学号、姓名、年龄
要求1: 再次添加一个学生对象,并在添加的时候进行学号的唯一性判断
要求2: 添加完毕之后,遍历所有学生信息。
要求3: 通过id删除学生信息
如果存在,则删除,如果不存在,则删除提示失败
要求4:删除完毕之后,遍历所有学生信息
要求5:查询数组ID为”2”的学生,如果存在,则将他的年龄在原基础上+1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public class Student { private Integer id; private String name; private Integer age;
public Student() { }
public Student(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age; }
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
|
public class StudentTest {
public static void main(String[] args) { Student[] arr = new Student[3]; Student s1 = new Student(1, "张三", 18); Student s2 = new Student(2, "李四", 18); Student s3 = new Student(3, "王五", 18);
arr[0] = s1; arr[1] = s2; arr[2] = s3;
Student s4 = new Student(4, "赵六", 20);
boolean flag = contains(arr, s4.getId()); if (flag) { System.out.println("当前ID重复"); } else { int count = getCount(arr); if (count == arr.length) { Student[] newArr = createNewArr(arr); newArr[count] = s4; printArr(newArr); System.out.println("-------"); int index = getIndex(newArr, 3); if (index >= 0) { newArr[index] = null; printArr(newArr); if (selectById(newArr, 2)) { System.out.println("该ID存在,且年龄自增成功"); printArr(newArr); } else { System.out.println("该ID不存在"); } } } else { arr[count] = s4; printArr(arr); System.out.println("-------"); int index = getIndex(arr, 3); if (index >= 0) { arr[index] = null; printArr(arr); if (selectById(arr, 2)) { System.out.println("该ID存在,且年龄自增成功"); printArr(arr); } else { System.out.println("该ID不存在"); } } } }
}
public static boolean selectById(Student[] arr, int id) { for (int i = 0; i < arr.length; i++) { if (arr[i] != null) { if (arr[i].getId() == id) { arr[i].setAge(arr[i].getAge() + 1); return true; } } } return false; }
public static int getIndex(Student[] arr, int id) { for (int i = 0; i < arr.length; i++) { if (arr[i] != null) { if (arr[i].getId() == id) { return i; } } } return -1; }
public static void printArr(Student[] arr) { for (int i = 0; i < arr.length; i++) { if (arr[i] != null) { System.out.println(arr[i].getId() + " " + arr[i].getName() + " " + arr[i].getAge()); } } }
public static Student[] createNewArr(Student[] arr) { Student[] newArr = new Student[arr.length + 1]; for (int i = 0; i < arr.length; i++) { newArr[i] = arr[i]; } return newArr; }
public static int getCount(Student[] arr) { int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] != null) { count++; } } return count; }
public static boolean contains(Student[] arr, int id) { for (int i = 0; i < arr.length; i++) { if (arr[i] != null) { if (arr[i].getId() == id) { return true; } } } return false; }
}
|
1.6 面向对象高级
1.6.1 static
关键字
static
表示静态,是Java
中的一个修饰符,可以修饰成员方法
,成员变量
被 stastc
修饰的成员变量,叫做静态变量
- 不属于对象,属于类
- 随着类的加载而加载,优先于对象的存在
被 static
修饰的成员方法,叫静态方法
特点: 将被该类所有对象共享
调用方式:
static 的注意事项
- 静态方法
只能
访问静态变量和静态方法
- 非静态方法
可以
访问静态变量或者静态方法,也可以访问非静态的成员变量和成员方法
- 静态方法是没有
this
关键字