封装
-
该露的露,该藏的藏
- 我们程序设计要追求**“高内聚,低耦合”。高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;低耦合∶仅暴露少量的方法给外部使用**
-
封装(数据的隐藏)
- 通常,应禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问,这称为信息隐藏
记住这句话就够了:属性私有,get/set
package oop.Demo01.demo04;
import oop.Demo01.demo04.Student;
/*
1.提高程序的安全性,保护数据
2.隐藏代码的实现细节
3.统一接口
4.系统的维护性增加了
*/
public class Application {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("冉耘滔");
System.out.println(s1.getName());
s1.setAge(710);//年龄不合法
System.out.println(s1.getAge());
}
}
/*
package oop.Demo01.demo04;
//类 private:私有
public class Student {
//属性私有
private String name;//名字
private int id;//学号
private char sex;//性别
private int age; //年龄
//提供一些可以操作这个属性的方法!
//提供一些public的get、set方法
//get 获得这个数据
public String getName(){
return this.name;
}
//set 给这个数据设置值
public void setName(String name){
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age>120 || age<0){
this.age = 3;
}else {
this.age = age;
}
}
}
//Alt + insert 自动生成
*/
继承
extends 扩展,子类是父类的扩展
Ctrl + H 展开继承关系树
单继承 ,一个儿子只能有一个爸爸
package oop.Demo01.demo05;
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.say();
System.out.println(student.getMoney());
}
}
package oop.Demo01.demo05;
//在Java中,所有的类,都默认直接或者间接继承object
//Person 父类
public class Person {
//public 一般
//private
//pretected
//default
private int money = 100000000;
public void say(){
System.out.println("说了一句话");
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
package oop.Demo01.demo05;
//学生 is 人 子类 派生类
//子类继承了父类 就会拥有父类的全部方法
public class Student extends Person {
}
package oop.Demo01.demo05;
//Teacher is 人 :子类 派生类
public class Teacher extends Person{
}
public class Student extends Person {
}
package oop.Demo01.demo05;
//Teacher is 人 :子类 派生类
public class Teacher extends Person{
}