01 封装
- 我们程序设计追求高内聚低耦合。
- 高内聚:类的内部数据操作细节自己完成,不允许外部干涉。
- 低耦合:仅暴露少量的方法给外部使用。
- 封装的意义:
- 提高程序的安全性,保护数据
- 隐藏代码的实现细节
- 统一接口
- 系统可维护增加了
- 属性私有,get/set
- 信息隐藏:禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问。
public class Student {
//属性私有
private String name;//姓名
private int id;//学号
private char sex;//性别
//get 获得这个数据
public String getName(){
return this.name;
}
//set 给这个数据设置值
public void setName(String name){
this.name = name;
}
}
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.setName("小方");
System.out.println(student.getName());
}
}
02 继承
- 继承的本质是对某一批类的抽象,从而实现对现实世界更好的建模。
- extends的意思是"扩展"。子类是父类的扩展。
- JAVA只有单继承,没有多继承。一个爸爸可以有多个儿子,一个儿子只能有一个爸爸。
- 继承是类与类之间的一种关系
public class Person {
public void say(){
System.out.println("hello");
}
}
public class Student extends Person {
}
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.say();//hello
}
}
- 私有的东西无法被继承。
- 在Java中,所有的类,都默认直接或者间接继承object
03 Super
-
super注意点:
- super调用父类的构造方法,必须在构造方法的第一个
- super必须只能出现在子类的方法或者构造方法中。
- super和this不能同时调用构造方法。
-
super VS this
- 代表的对象不同:this(本身调用这个对象),super(代表父类对象的引用)。
- 前提:this(没有继承也可以使用),super(只有在继承条件下才可以使用)。
- 构造方法:this():本类的构造,super():父类的构造
public class Person { public Person(){ System.out.println("Person无参"); } protected String name = "xiaofang"; public void print(){ System.out.println("Person"); } } public class Student extends Person { //隐藏代码:调用父类的无参构造 public Student(){ super(); System.out.println("Student无参"); } private String name = "xiaoxu"; public void print(){ System.out.println("student"); } public void test(String name){ System.out.println(name);//方 System.out.println(this.name);//xiaoxu System.out.println(super.name);//xiaofang } public void test1(){ print();//student this.print();//student super.print();//Person } } public class Application { public Application() { } public static void main(String[] args) { Student student = new Student();//先调用父类Person无参,在调用子类Student无参 student.test("方"); student.test1(); } }