2023.2.15学习日志
面向对象有三大特性,分别是:封装、继承和多态。
封装
将一个系统的内容限定在系统的内部,内容的联系与操作尽量在系统的内部进行,只暴露少量的方法让外部可以对系统内容进行操作。
访问级别限定修饰符:
private:同一个类中可使用
default:默认限定级别,省略,在同一个包中可使用
protected:同一个包中的类或者子类可使用
public:对外公开
修饰词 | 类 | 包 | 子类 | 其他包 |
private | √ | × | × | × |
default | √ | √ | × | × |
protected | √ | √ | √ | × |
public | √ | √ | √ | √ |
封装实例
public class Phone {
//1.定义手机类,手机有品牌(brand),价格(price)和颜色(color)三个属性,有打电话call()和sendMessage()两个功能。
//2.请定义出手机类,类中要有空参、有参构造方法,set/get方法。
//3.定义测试类,在主方法中使用空参构造创建对象,使用set方法赋值。
//属性
private String brand;//品牌
private int price;//价格
private String color;//颜色
//构造器
public Phone() {
}
public Phone(String brand, int 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 int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
//打电话
public void call() {
System.out.println("正在使用价格为" + getPrice() + "元" + getColor() + "的" + getBrand() + "手机打电话....");
}
public void sendMessage() {
System.out.println("正在使用价格为" + getPrice() + "元" + getColor() + "的" + getBrand() + "手机发短信....");
}
}
继承
让某个类型的对象获得另一个类型的对象的属性和方法。子类继承父类,使得子类对象可以获得父类的属性和方法。
语法:
clas A extend B{}
子类继承父类,子类获得父类的方法,当子类对父类的方法不满意时,子类可以对该方法进行重写(重写和重载是完全不同的两个概念),从而实现新的逻辑。
重写实例
public class Animal {//动物类
private int age;
public Animal() {
}
public Animal(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void eat(){
System.out.println("是动物就要吃东西");
}
}
public class Dog extends Animal{//子类 狗类
@Override
public void eat() {//重写eat方法
System.out.println("狗吃骨头");
}
}
多态
多态:对于同一个行为,不同的子类对象具有不同的表现形式。多态存在的3个条件:
继承 2)重写 3)父类引用指向子类对象。
多态实例
public class Animal {
public void eat(){
System.out.println("是动物就要吃东西");
}
}
public class Cat extends Animal{
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
public class Dog extends Animal{
@Override
public void eat() {
System.out.println("狗吃骨头");
}
}
public class Pig extends Animal{
@Override
public void eat() {
System.out.println("猪啥都吃");
}
}
public class Test {
public static void main(String[] args) {
Animal d = new Dog();
Animal c = new Cat();
Animal p = new Pig();
d.eat();
c.eat();
p.eat();
}
}
运行结果
![](https://img-blog.csdnimg.cn/img_convert/43ac6f6f6a226e546d3a5dc6eef0a43e.png)