引言
在面向对象编程的世界里,封装、继承和多态构成了核心的三大特性。本文将深入探讨这些概念,并通过Java代码示例来阐释它们的重要性和实际应用。
1. 封装
1.1 什么是封装呢?
封装是一种隐藏对象的内部状态和复杂性,只对外暴露有限接口的设计原则。就像我们日常使用的电子产品,它们将复杂的内部结构封装起来,只展示用户需要操作的部分。
在Java中,封装通过访问限定符实现,它控制着类成员的可见性和访问级别。
1.2 访问限定符
范围 | private | default | protected | public |
---|---|---|---|---|
同一包内 | ❌ | ✅ | ✅ | ✅ |
同一包不同类 | ❌ | ❌ | ✅ | ✅ |
不同包子类 | ❌ | ❌ | ✅ | ✅ |
不同包非子类 | ❌ | ❌ | ❌ | ✅ |
public
:对所有类可见。protected
:对同一包内的类和所有子类可见。default
:对同一包内的类可见。private
:仅对定义它的类可见。
1.3 使用封装
下面是一个Watch
类的示例,展示了如何使用封装来隐藏和保护类的内部状态。
package cn.nyist.watch;
public class Watch {
private String machine; // 动力来源
public String time; // 时间
String brand; // 品牌,default
public Watch(String machine, String time, String brand) {
this.machine = machine;
this.time = time;
this.brand = brand;
}
public void seeTime() {
System.out.println("时间");
}
private void debug() {
System.out.println("调试零件");
}
}
在Watch
类中,main
函数模拟了手表的创造者,可以访问所有成员:
public static void main(String[] args) {
Watch w = new Watch("机械", "12:00", "劳力士");
System.out.println(w.machine);
System.out.println(w.time);
System.out.println(w.brand);
w.seeTime();
w.debug();
}
而在Buy
类中,模拟了手表的购买者,只能访问公共成员:
package cn.nyist.watch;
public class Buy {
public static void main(String[] args) {
Watch w = new Watch("机械", "12:00", "劳力士");
System.out.println(w.time); // time是public属性
System.out.println(w.brand); // brand是default属性
w.seeTime(); // seeTime是public属性
}
}
在其他包中的People
类,只能访问Watch
类的公共成员:
public class People {
public static void main(String[] args) {
Watch w = new Watch("机械", "12:00", "劳力士");
System.out.println(w.time); // time是public属性
w.seeTime(); // seeTime是public属性
}
}
2. 继承
2.1 为什么要有继承?
继承允许我们创建新的类,这些新类可以继承现有类的属性和方法,从而避免代码冗余,并实现代码复用。
package cn.nyist.animal;
public class Dog {
public String name;
public String color;
protected int age;
public Dog(String name, String color, int age) {
this.name = name;
this.color = color;
this.age = age;
}
public void eat() {
System.out.println("吃饭~");
}
public void sleep() {
System.out.println("睡觉~");
}
public void bark() {
System.out.println("汪汪~");
}
}
```java
package cn.nyist.animal;
public class Cat {
public String name;
public String color;
protected int age;
public Cat
文章整理自互联网,只做测试使用。发布者:Lomu,转转请注明出处:https://www.it1024doc.com/4552.html