Day16-Java
面向对象
封装(数据的隐藏)
- 程序设计要追求“高内聚,低耦合”,高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;低耦合就是仅暴露少量方法给外部使用
- 封装通常应该禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问,这称为信息隐藏
- 属性私有,get/set
package com.Kong.Oop.demo03;
public class Student {
//属性私有private
private String name;
private int id;
private char sex;
private int age;
//提供一些可以操作这个属性的方法
//提供一些public的get,set方法
//get 获得这个数据
public String getName() {
return 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 < 0 || age > 100) {
System.out.println("年龄错误");
this.age = -1;
}else {
this.age = age;
}
}
}
package com.Kong.Oop;
import com.Kong.Oop.demo03.Student;
/*
* 1.提高程序的安全性,保护数据
* 2.隐藏代码的实现细节
* 3.统一接口
* 4.系统可维护增加了
* */
public class Application {
public static void main(String[] args) {
Student s1=new Student();
s1.setName("Kongmi");
System.out.println(s1.getName());
s1.setAge(999);//不合法
System.out.println(s1.getAge());
}
}
继承
-
继承的本质就是对某一批类的抽象,从而实现对现实世界更好的建模
-
extends的意思是“扩展”,子类是父类的扩展
-
Java中类只有单继承,没有多继承
-
继承是类和类之间的一种关系,继承关系的两个类,一个为子类(派生类),一个为父类(基类),子类继承父类,使用关键字extends来表示
-
在Java中,所有的类都默认继承Object类
package com.Kong.Oop;
import com.Kong.Oop.demo04.Person;
import com.Kong.Oop.demo04.Student;
public class Application {
public static void main(String[] args) {
Student s1 = new Student();
s1.say();
s1.setMoney(10000);
}
}
package com.Kong.Oop.demo04;
//在Java中,所有的类都默认继承Object类
//父类
public class Person {
private int money=10_0000_0000;
public void say(){
System.out.println("Hello");
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
package com.Kong.Oop.demo04;
//子类
public class Student extends Person {
}
Super/This
super:
- super调用父类的构造方法,必须在构造方法的第一个
- super必须只能出现在子类的方法或者构造方法中
- super和this不能同时调用构造方法
| super | this |
|---|---|
| 代表父类对象的应用 | 调用者本身这个对象 |
| 只能在继承条件才能使用 | 没继承也能使用 |
| 父类的构造 | 本类的构造 |
package com.Kong.Oop.demo04;
//在Java中,所有的类都默认继承Object类
//父类
public class Person {
public Person() {
System.out.println("Person无参执行");
}
}
package com.Kong.Oop.demo04;
//子类
public class Student extends Person {
public Student() {
//隐藏了父类的无参构造
super();//调用父类的构造器,必须要在子类的第一行
System.out.println("Student无参执行");
}
}
package com.Kong.Oop;
import com.Kong.Oop.demo04.Student;
public class Application {
public static void main(String[] args) {
Student s1=new Student();
}
}
浙公网安备 33010602011771号