--- title: "00-类与接口" created: 2025-12-02 tags: - 项目 aliases: - 类与接口 --- # 类与接口 ## 类 class与C++、Python类似。 ### 源文件声明规则 - 一个源文件中只能有一个public类。(publiv class Main) - 一个源文件可以有多个非public类。 - 源文件的名称应该和public类的类名保持一致。 - 每个源文件中,先写package语句,再写import语句,最后定义类。 ### 类的定义 public: 所有对象均可以访问 private: 只有自己可以访问 ```java class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public int getX() { return x; } public int getY() { return y; } public String toString() { return String.format("(%d, %d)", x, y); } } ``` ### 类的继承 每个类只能继承一个类。 ```java class ColorPoint extends Point { private String color; public ColorPoint(int x, int y, String color) { super(x, y); this.color = color; } public void setColor(String color) { this.color = color; } public String toString() { return String.format("(%d, %d, %s)", super.getX(), super.getY(), this.color); } } ``` ### 类的多态 ```java public class Main { public static void main(String[] args) { Point point = new Point(3, 4); Point colorPoint = new ColorPoint(1, 2, "red"); // 多态,同一个类的实例,调用相同的函数,运行结果不同 System.out.println(point.toString()); System.out.println(colorPoint.toString()); } } ``` ## 接口 interface与class类似。主要用来定义类中所需包含的函数。 接口也可以继承其他接口,一个类可以实现多个接口。 ### 接口的定义 ```java interface Role { public void greet(); public void move(); public int getSpeed(); } ``` ### 接口的继承 每个接口可以继承多个接口 ```java interface Hero extends Role { public void attack(); } ``` ### 接口的实现 每个类可以实现多个接口 ```java class Zeus implements Hero { private final String name = "Zeus"; public void attack() { System.out.println(name + ": Attack!"); } public void greet() { System.out.println(name + ": Hi!"); } public void move() { System.out.println(name + ": Move!"); } public int getSpeed() { return 10; } } ``` ### 接口的多态 ```java class Athena implements Hero { private final String name = "Athena"; public void attack() { System.out.println(name + ": Attack!"); } public void greet() { System.out.println(name + ": Hi!"); } public void move() { System.out.println(name + ": Move!"); } public int getSpeed() { return 10; } } public class Main { public static void main(String[] args) { Hero[] heros = {new Zeus(), new Athena()}; for (Hero hero: heros) { hero.greet(); } } } ``` ## 泛型 类似于C++的template,Java的类和接口也可以定义泛型,即同一套函数可以作用于不同的对象类型。 泛型只能使用对象类型,不能使用基本变量类型。 ## 练习题 [[05-在O(1)时间删除链表结点|在O(1)时间删除链表结点]] [[04-反转链表|反转链表]] [[02-从尾到头打印链表|从尾到头打印链表]] [[03-删除链表中重复的节点|删除链表中重复的节点]] [[01-三元组排序|三元组排序]] --- **项目分区导航**: [[05-邻值查找|邻值查找]] ⬅️ | 00-类与接口 | ➡️ [[01-三元组排序|三元组排序]]