课程笔记Day09
- 封装
- 权限修饰符
- 继承
- final 关键字
第一章 封装
第01节 基础理论
面向对象三大特性
1. 封装性
2. 继承性
3. 多态性
什么是封装呢?
类的封装
封装就是对 一些属性和行为的包装。将属性和行为包装成为类。通过创建对象的方式,去使用属性和行为。
生活实例:
有一个名字叫旺财的事物,他有3岁,可以看家,可以吃肉,还可以卖萌,还可以溜。
那么我们将这种 属性和行为封装成为狗。
使用狗的对象,就可以完成上面的操作(旺财、3岁、看家、卖萌....)
方法封装
我们将一些常用的写法,常用的逻辑,封装成为一个方法,直接调用方法就可以了。
例如:如果我们对于数组的循环遍历,操作比较多。这种情况下,我们就可以将数组的循环遍历,封装成为方法。
系统提供了一个方法 Arrays.toString(数组名称); 这里 toString()方法当中的细节,不让你看到,直接丢参数,得到结果就可以。
属性封装
有时候,我们需要将属性(成员变量)隐藏起来,不让外界访问,这种情况下可以使用 private 关键字。
这里如果采用 private 去修饰成员变量,外界是不能直接访问的。这也是属性封装的一种体现。
第02节 private封装
案例代码
学生类
//学生类
public class Student {
String name;
private int age;
//构造方法
public Student(String name, int age) {
this.name = name;
if(age>=0 && age < 400) {
this.age = age;
}
}
public void show(){
System.out.println("name = " + name);
System.out.println("age = " + age);
}
}
学生类
//测试类
public class Test {
public static void main(String[] args) {
//创建对象
//Student stu = new Student();
//stu.name = "赵兴哲";
//stu.age = -20;
Student stu = new Student("赵兴哲",-20);
stu.show();
}
}
效果图
第03节 JavaBean
理论说明
JavaBean 是类的一种标准写法:包含有
1. 成员变量 private修饰
2. 成员方法 getXxx 和 setXxx
3. 构造方法 无参数构造方法 和 全参数构造方法
快捷键:
在代码区域,右键选择 Gener... 生成构造方法 Con... 生成 getter And setter
案例代码
手机类
//手机类
public class Phone {
//成员变量
private String brand;
private int price;
public Phone() {
}
public Phone(String brand, int price) {
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
测试类
//测试类
public class Test {
public static void