【JAVA】Java基础—面向对象编程:类的定义

编者:之前对JAVA的基础语法,面向对象编程基础进行了介绍,但这方面内容是面向对象的核心,理解OOP概念需要一定时间,所以,我们对这块内容细化进行子主题介绍。

一、类的基本概念

在Java中,类的定义包括以下几个部分:

  1. 类的声明:使用class关键字定义一个类。

  2. 属性(字段):类的状态或特征,通常用变量表示。

  3. 方法:类的行为或功能,通常用函数表示。

  4. 构造函数:用于创建对象的特殊方法。

二、类的定义示例

示例 1:简单的类定义

代码示例

// 定义一个简单的类 Car
public class Car {
    // 属性(字段)
    String color; // 颜色
    String model; // 型号
    int year; // 年份

    // 构造函数
    public Car(String color, String model, int year) {
        this.color = color; // 使用参数初始化属性
        this.model = model;
        this.year = year;
    }

    // 方法:显示汽车信息
    public void displayInfo() {
        System.out.println("Car Model: " + model);
        System.out.println("Car Color: " + color);
        System.out.println("Car Year: " + year);
    }
}

// 主类,用于测试 Car 类
public class Main {
    public static void main(String[] args) {
        // 创建 Car 类的对象
        Car myCar = new Car("Red", "Toyota", 2020);
        
        // 调用方法显示汽车信息
        myCar.displayInfo();
    }
}

代码解释

  1. 类的声明public class Car定义了一个名为Car的类。

  2. 属性String colorString modelint yearCar类的属性,分别表示汽车的颜色、型号和年份。

  3. 构造函数public Car(String color, String model, int year)是构造函数,用于初始化新创建的对象的属性。this关键字用于区分类的属性和构造函数的参数。

  4. 方法public void displayInfo()是一个方法,用于输出汽车的信息。

  5. 对象创建:在Main类的main方法中,使用new Car("Red", "Toyota", 2020)创建了一个Car对象,并调用displayInfo方法显示汽车信息。

三、类的进一步扩展

在实际应用中,类可以更加复杂,包含更多的功能和特性。下面我们将介绍一些常见的扩展特性。

1. 方法重载

方法重载是指在同一个类中,可以定义多个同名但参数不同的方法。

示例 2:方法重载

public class Calculator {
    // 加法:两个整数
    public int add(int a, int b) {
        return a + b;
    }

    // 加法:三个整数
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    // 加法:两个浮点数
    public double add(double a, double b) {
        return a + b;
    }
}

// 主类,用于测试 Calculator 类
public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        
        // 调用不同的 add 方法
        System.out.println("Add two integers: " + calc.add(5, 10));
        System.out.println("Add three integers: " + calc.add(5, 10, 15));
        System.out.println("Add two doubles: " + calc.add(5.5, 10.5));
    }
}

代码解释

  1. Calculator类中定义了三个add方法,分别处理不同数量和类型的参数。

  2. Main类中,创建Calculator对象并调用不同的add方法,展示了方法重载的使用。

2. 继承

继承是OOP的重要特性,允许一个类继承另一个类的属性和方法,从而实现代码重用。

示例 3:继承

// 基类
public class Vehicle {
    String brand; // 品牌

    public Vehicle(String brand) {
        this.brand = brand;
    }

    public void honk() {
        System.out.println("Beep! Beep!");
    }
}

// 派生类
public class Bike extends Vehicle {
    int gears; // 齿轮数

    public Bike(String brand, int gears) {
        super(brand); // 调用基类构造函数
        this.gears = gears;
    }

    public void displayInfo() {
        System.out.println("Bike Brand: " + brand);
        System.out.println("Number of Gears: " + gears);
    }
}

// 主类,用于测试 Bike 类
public class Main {
    public static void main(String[] args) {
        Bike myBike = new Bike("Giant", 21);
        
        // 调用方法
        myBike.honk(); // 继承的方法
        myBike.displayInfo(); // 自己的方法
    }
}

代码解释

  1. Vehicle类是基类,包含品牌和喇叭的方法。

  2. Bike类继承自Vehicle类,增加了gears属性和displayInfo方法。

  3. Main类中,创建Bike对象,调用继承自Vehiclehonk方法和Bike类自己的displayInfo方法。

3. 封装

封装是OOP的另一个重要特性,通过访问修饰符控制对类属性和方法的访问。

示例 4:封装

public class Account {
    // 私有属性
    private String accountNumber;
    private double balance;

    // 构造函数
    public Account(String accountNumber) {
        this.accountNumber = accountNumber;
        this.balance = 0.0; // 初始余额为0
    }

    // 公共方法:存款
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: " + amount);
        } else {
            System.out.println("Deposit amount must be positive.");
        }
    }

    // 公共方法:取款
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrew: " + amount);
        } else {
            System.out.println("Insufficient funds or invalid amount.");
        }
    }

    // 公共方法:查看余额
    public double getBalance() {
        return balance;
    }
}

// 主类,用于测试 Account 类
public class Main {
    public static void main(String[] args) {
        Account myAccount = new Account("123456789");
        
        myAccount.deposit(1000);
        System.out.println("Current Balance: " + myAccount.getBalance());
        
        myAccount.withdraw(500);
        System.out.println("Current Balance: " + myAccount.getBalance());
        
        myAccount.withdraw(600); // 尝试取款超过余额
    }
}

代码解释

  1. Account类的属性accountNumberbalance被声明为私有,外部无法直接访问。

  2. 提供公共方法depositwithdrawgetBalance来操作账户余额,确保了数据的安全性。

  3. Main类中,创建Account对象并调用公共方法,展示了封装的效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值