《零基础学Java编程:手把手教你写出第一个可运行的程序 - 基础知识篇七》

目录

一 . 抽象类

        1 . 基本定义

        2 . 模板设计模式

二 . 包装类

        1 . 装箱和拆箱

        2 . 数据类型转换

三 . 接口

        1 . 基本定义

2 . 适配器设计模式

3 . 接口和抽象类的区别

四 . 泛型

        1 . 基本定义

        2 . 泛型通配符

3 . 泛型接口

4 . 泛型方法


一 . 抽象类

        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();
    }
}

二 . 包装类

基本类型与包装类对应表
基本类型包装类
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

(博哥有话说: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 . 接口和抽象类的区别

接口和抽象类的区别
特性接口抽象类
关键字interfaceabstract 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"));
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

博哥爱学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值