隐藏对象内部属性与实现细节,仅暴露公共接口,控制属性访问权限。
private,提供 getXxx()/setXxx() 方法。public/private。toString() 便于调试。目的:增强安全性、简化调用、降低耦合。
通过 extends 实现代码复用。Java 单继承,所有类隐式继承 Object。
private 成员。super()。分编译时多态(重载)与运行时多态(重写/覆盖)。
class A { String show(D o) { return "A and D"; } String show(A o) { return "A and A"; } }
class B extends A { String show(B o) { return "B and B"; } String show(A o) { return "B and A"; } }
class C extends B {}
class D extends B {}
public class Test {
public static void main(String[] args) {
A a1 = new A(); A a2 = new B(); B b = new B(); C c = new C(); D d = new D();
System.out.println("1--" + a1.show(b)); // A and A
System.out.println("2--" + a1.show(c)); // A and A
System.out.println("3--" + a1.show(d)); // A and D
System.out.println("4--" + a2.show(b)); // B and A
System.out.println("5--" + a2.show(c)); // B and A
System.out.println("6--" + a2.show(d)); // A and D
System.out.println("7--" + b.show(b)); // B and B
System.out.println("8--" + b.show(c)); // B and B
System.out.println("9--" + b.show(d)); // A and D
}
}
核心规则:
a2.show(b),a2 编译类型 A,A 中无 show(B),向上查找找到 show(A),B 重写了该方法 → 执行 B.show(A) → B and A。a1.show(d),A 有 show(D) → 直接执行 A.show(D) → A and D。super():子类构造器首行调用父类构造器。super.method():调用父类被重写的方法。super.field:访问父类被隐藏的字段。封装、继承、多态是面向对象基石。实战中:高内聚低耦合,优先组合,谨慎继承,善用接口多态实现可扩展架构。