目录
一 . 抽象类
1 . 基本定义
- 使用
abstract关键字声明 - 不能直接实例化,必须通过子类继承
- 可以包含抽象方法(无方法体)和具体方法
- 可以包含成员变量、构造方法、普通方法
- 子类必须实现所有抽象方法,除非子类也是抽象类
(博哥有话说:抽象类是有方法名没有方法体)
abstract class Shape {
private String color;
public Shape(String color) {
this.color = color;
}
// 抽象方法 - 无实现
public abstract double calculateArea();
// 具体方法
public String getColor() {
return color;
}
}
class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Shape circle = new Circle("Red", 5.0);
System.out.println("Circle color: " + circle.getColor());
System.out.println("Circle area: " + circle.calculateArea());
}
}
2 . 模板设计模式
- 定义算法骨架,将具体步骤延迟到子类实现
- 抽象类定义模板方法(通常为final防止修改)
- 子类实现可变部分
(博哥有话说:在创建抽象类的时候不能用final修饰,因为它需要通过覆写实现,但是抽象方法可以使用final修饰)
abstract class Game {
// 模板方法 - 定义游戏流程
public final void play() {
initialize();
startPlay();
endPlay();
}
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
}
class Cricket extends Game {
@Override
void initialize() {
System.out.println("Cricket Game Initialized");
}
@Override
void startPlay() {
System.out.println("Cricket Game Started");
}
@Override
void endPlay() {
System.out.println("Cricket Game Finished");
}
}
public class TemplatePatternDemo {
public static void main(String[] args) {
Game game = new Cricket();
game.play();
}
}
二 . 包装类
| 基本类型 | 包装类 |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
(博哥有话说:byte,short,long,float,double,boolean这几个基本类型的包装类将首字母大写即可,但是特殊的int,char需要特殊记住)
1 . 装箱和拆箱
- 装箱:基本类型 → 包装类 (
Integer.valueOf()或自动装箱) - 拆箱:包装类 → 基本类型 (
intValue()或自动拆箱) - 缓存机制:-128到127的Integer对象会被缓存
public class BoxingUnboxing {
public static void main(String[] args) {
// 手动装箱
Integer a = Integer.valueOf(100);
// 自动装箱
Integer b = 200;
// 手动拆箱
int c = a.intValue();
// 自动拆箱
int d = b;
System.out.println("a: " + a + ", c: " + c);
System.out.println("b: " + b + ", d: " + d);
// 缓存测试
Integer x = 100;
Integer y = 100;
System.out.println(x == y); // true (使用缓存)
Integer m = 200;
Integer n = 200;
System.out.println(m == n); // false (新建对象)
}
}
2 . 数据类型转换
- 字符串 ↔ 基本类型:
parseXxx() - 包装类 ↔ 基本类型:
valueOf()和xxxValue() - 进制转换:
toBinaryString(),toHexString()等
public class TypeConversion {
public static void main(String[] args) {
// 字符串 → 基本类型
String numStr = "123";
int num = Integer.parseInt(numStr);
double d = Double.parseDouble("3.14");
// 基本类型 → 字符串
String intStr = Integer.toString(456);
String doubleStr = Double.toString(2.718);
// 进制转换
String binary = Integer.toBinaryString(10);
String hex = Integer.toHexString(255);
System.out.println("Parsed int: " + num);
System.out.println("Binary of 10: " + binary);
System.out.println("Hex of 255: " + hex);
// 自动类型转换
Double doubleObj = 3.14;
double primitiveDouble = doubleObj; // 自动拆箱
Integer intObj = (int) primitiveDouble; // 强制转换后再装箱
System.out.println("Converted Integer: " + intObj);
}
}
三 . 接口
1 . 基本定义
- 使用
interface关键字定义 - 方法默认是
public abstract - 常量默认是
public static final
interface Vehicle {
// 抽象方法
void start();
void stop();
// 默认方法
default void honk() {
System.out.println("Beep beep!");
}
// 静态方法
static int getMaxSpeed() {
return 120;
}
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
@Override
public void stop() {
System.out.println("Car stopped");
}
// 可以重写默认方法
@Override
public void honk() {
System.out.println("Car honking: Honk honk!");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Car car = new Car();
car.start();
car.honk();
car.stop();
System.out.println("Max speed: " + Vehicle.getMaxSpeed());
}
}
2 . 适配器设计模式
- 将一个接口转换成客户端期望的另一个接口
- 通过抽象类实现接口所有方法(空实现)
- 子类只需重写需要的方法
interface MediaPlayer {
void play(String audioType, String fileName);
}
interface AdvancedMediaPlayer {
void playVlc(String fileName);
void playMp4(String fileName);
}
class VlcPlayer implements AdvancedMediaPlayer {
@Override
public void playVlc(String fileName) {
System.out.println("Playing vlc file: " + fileName);
}
@Override
public void playMp4(String fileName) {
// 不做任何事
}
}
class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType) {
if(audioType.equalsIgnoreCase("vlc")) {
advancedMusicPlayer = new VlcPlayer();
}
}
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")) {
advancedMusicPlayer.playVlc(fileName);
}
}
}
public class AdapterPatternDemo {
public static void main(String[] args) {
MediaPlayer player = new MediaAdapter("vlc");
player.play("vlc", "song.vlc");
}
}
3 . 接口和抽象类的区别
| 特性 | 接口 | 抽象类 |
|---|---|---|
| 关键字 | interface | abstract class |
| 实例化 | 不能 | 不能 |
| 方法实现 | Java 8前不能有实现 | 可以有具体方法 |
| 变量 | 只能是public static final常量 | 可以是普通变量 |
| 构造方法 | 不能有 | 可以有 |
| 多继承 | 一个类可实现多个接口 | 一个类只能继承一个抽象类 |
| 设计目的 | 定义行为规范 | 提供通用实现,定义模板 |
| 默认方法 | Java 8+支持 | 一直支持 |
| 访问修饰符 | 默认public | 可以是任意访问修饰符 |
(博哥有话说:这张表最好记住,如果很费劲可以多次实践来检测)
四 . 泛型
(博哥有话说:泛型是指不知道具体是什么数据类型,检测到是什么数据类型,执行哪个方法一般在底层使用)
1 . 基本定义
- 编译时类型安全检查
- 避免类型转换
- 类型参数约定:T-类型,E-元素,K-键,V-值,N-数字
- 类型擦除:运行时泛型信息被擦除
class GenericBox<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
public void showType() {
System.out.println("Type of T is: " + content.getClass().getName());
}
}
public class GenericBasic {
public static void main(String[] args) {
GenericBox<String> stringBox = new GenericBox<>();
stringBox.setContent("Hello Generics");
System.out.println(stringBox.getContent());
stringBox.showType();
GenericBox<Integer> intBox = new GenericBox<>();
intBox.setContent(123);
System.out.println(intBox.getContent());
intBox.showType();
}
}
2 . 泛型通配符
?- 未知类型? extends T- 上界通配符(T及其子类)? super T- 下界通配符(T及其父类)
import java.util.List;
import java.util.ArrayList;
public class WildcardExample {
// 上界通配符 - 只能读取
public static double sumOfList(List<? extends Number> list) {
double sum = 0.0;
for (Number num : list) {
sum += num.doubleValue();
}
return sum;
}
// 下界通配符 - 可以写入
public static void addNumbers(List<? super Integer> list) {
for (int i = 1; i <= 5; i++) {
list.add(i);
}
}
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>();
addNumbers(intList);
System.out.println("Sum of integers: " + sumOfList(intList));
List<Double> doubleList = List.of(1.1, 2.2, 3.3);
System.out.println("Sum of doubles: " + sumOfList(doubleList));
List<Number> numList = new ArrayList<>();
addNumbers(numList);
System.out.println("Number list: " + numList);
}
}
3 . 泛型接口
- 接口可以定义类型参数
- 实现类可以指定具体类型或保持泛型
- 常用于工厂模式、策略模式等
// 泛型接口
interface Repository<T, ID> {
void save(T entity);
T findById(ID id);
void delete(ID id);
}
// 具体实现
class UserRepository implements Repository<User, String> {
@Override
public void save(User user) {
System.out.println("Saving user: " + user.getName());
}
@Override
public User findById(String id) {
return new User(id, "User " + id);
}
@Override
public void delete(String id) {
System.out.println("Deleting user with id: " + id);
}
}
class User {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
}
public class GenericInterfaceDemo {
public static void main(String[] args) {
UserRepository repo = new UserRepository();
User user = repo.findById("001");
repo.save(user);
repo.delete("001");
}
}
4 . 泛型方法
- 在方法返回类型前声明类型参数
- 可以用于静态和非静态方法
- 类型参数作用域仅限于方法内
public class GenericMethodExample {
// 泛型方法
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}
// 有界的泛型方法
public static <T extends Comparable<T>> T max(T x, T y, T z) {
T max = x;
if (y.compareTo(max) > 0) {
max = y;
}
if (z.compareTo(max) > 0) {
max = z;
}
return max;
}
public static void main(String[] args) {
// 调用泛型方法
Integer[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"A", "B", "C"};
printArray(intArray);
printArray(strArray);
// 调用有界泛型方法
System.out.println("Max of 3, 5, 1: " + max(3, 5, 1));
System.out.println("Max of pear, apple, orange: " +
max("pear", "apple", "orange"));
}
}

被折叠的 条评论
为什么被折叠?



