讲师中心 微信公众号

工具推荐

视频效率加速
AniShort
AniShort

AI短剧协同制作平台

Seko
Seko

AI短剧一键生成成片

剧云
剧云

中文短剧剧本制作平台

updream

一键生成高质量推广成片

正确处理Java继承中子类方法对父类属性的修改

梦雪大大_1867

梦雪大大_1867

发布时间:2025-10-30 18:32:17

|

977人浏览过

|

来源于php中文网

原创

正确处理java继承中子类方法对父类属性的修改

本文旨在解决Java继承中子类方法修改父类属性时遇到的值无法保持的问题。通过分析问题代码,明确原因在于子类方法中创建了局部变量而非修改父类属性,并提供使用`setter`方法正确更新父类属性的解决方案,从而保证子类方法对父类状态的修改能够生效。

在Java的继承关系中,子类可以继承父类的属性和方法。然而,当子类的方法需要修改父类的属性时,如果不注意处理,可能会出现修改无效的情况。本文将通过一个具体的例子,分析这种问题的原因,并提供正确的解决方案。

问题分析

考虑以下代码,其中BaseAccount是父类,DebitCard是子类,DebitCard的withdraw方法旨在扣除账户余额。

立即学习“Java免费学习笔记(深入)”;

public class BaseAccount {

    private double opening;
    private double currentAmount = 0.0;
    private double amount;

    public BaseAccount(double opening, double currentAmount, double amount) {
        this.opening = opening;
        this.currentAmount = currentAmount;
        this.amount = amount;
    }

    public double getOpening() {
        return opening;
    }

    public void setOpening(double opening) {
        this.opening = opening;
    }

    public double getCurrentAmount() {
        return currentAmount;
    }

    public void setCurrentAmount(double currentAmount) {
        this.currentAmount = currentAmount;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    public String opening(double opening) {
        this.opening = opening;
        this.currentAmount = currentAmount + opening;
        return "This account has been opened with " + this.opening;
    }

    public String deposit(double amount) {
        this.currentAmount += amount;
        return "Depositing " + amount;
    }

    public String balance() {
        return "Balance: " + currentAmount;
    }
}

public class DebitCard extends BaseAccount{

    public DebitCard(double opening, double currentAmount, double amount) {
        super(opening, currentAmount, amount);
    }

    public String withdraw(double amount) {
        double currentAmount = getCurrentAmount() - amount;
        return amount + " have been retired. \nBalance: " + currentAmount;
    }
}

public class Inheritance {

    public static void main(String[] args) {
        BaseAccount base1 = new BaseAccount(0,0,0);
        System.out.println(base1.opening(500));
        System.out.println(base1.deposit(22.22));
        System.out.println(base1.balance());

        DebitCard debit1 = new DebitCard(0,0,0);
        System.out.println(debit1.opening(400));
        System.out.println(debit1.deposit(33.33));
        System.out.println(debit1.balance());
        System.out.println(debit1.withdraw(33.33));
        System.out.println(debit1.balance());
    }
}

运行上述代码,会发现DebitCard的withdraw方法似乎没有生效,最后的账户余额仍然是存款后的余额,而不是扣除后的余额。

问题出在DebitCard的withdraw方法中:

Java调试
Java调试

通过 JDWP 实现 Java 远程调试:连接远程 JVM、设置断点、单步执行代码、查看变量值、获取调用栈。适用于需要调试远程 Java 应用、排查运行时状态、追踪代码执行流程的场景。 术语注解 JDWP:Java Debug Wire Protocol,Java 调试有线协议(Java 远程调试底层通信协议) remote JVM:远程 Java 虚拟机 step through code:代码单步调试(步入 / 步过 / 步出调试) inspect variables:变量查看 / 变量检视 stac

下载
public String withdraw(double amount) {
    double currentAmount = getCurrentAmount() - amount;
    return amount + " have been retired. \nBalance: " + currentAmount;
}

这行代码 double currentAmount = getCurrentAmount() - amount; 声明了一个局部变量 currentAmount,它与父类BaseAccount中的 currentAmount 属性不是同一个变量。因此,对这个局部变量的修改不会影响父类的属性值。

解决方案

要解决这个问题,需要使用父类的 setCurrentAmount 方法来更新父类的 currentAmount 属性。修改后的 withdraw 方法如下:

public String withdraw(double amount) {
    double newCurrentAmount = getCurrentAmount() - amount;
    setCurrentAmount(newCurrentAmount);
    return amount + " have been retired. \nBalance: " + newCurrentAmount;
}

在这个修改后的版本中,首先计算新的余额,然后通过 setCurrentAmount(newCurrentAmount) 方法将新的余额设置回父类的 currentAmount 属性。

完整代码示例

public class BaseAccount {

    private double opening;
    private double currentAmount = 0.0;
    private double amount;

    public BaseAccount(double opening, double currentAmount, double amount) {
        this.opening = opening;
        this.currentAmount = currentAmount;
        this.amount = amount;
    }

    public double getOpening() {
        return opening;
    }

    public void setOpening(double opening) {
        this.opening = opening;
    }

    public double getCurrentAmount() {
        return currentAmount;
    }

    public void setCurrentAmount(double currentAmount) {
        this.currentAmount = currentAmount;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    public String opening(double opening) {
        this.opening = opening;
        this.currentAmount = currentAmount + opening;
        return "This account has been opened with " + this.opening;
    }

    public String deposit(double amount) {
        this.currentAmount += amount;
        return "Depositing " + amount;
    }

    public String balance() {
        return "Balance: " + currentAmount;
    }
}

public class DebitCard extends BaseAccount{

    public DebitCard(double opening, double currentAmount, double amount) {
        super(opening, currentAmount, amount);
    }

    public String withdraw(double amount) {
        double newCurrentAmount = getCurrentAmount() - amount;
        setCurrentAmount(newCurrentAmount);
        return amount + " have been retired. \nBalance: " + newCurrentAmount;
    }
}

public class Inheritance {

    public static void main(String[] args) {
        BaseAccount base1 = new BaseAccount(0,0,0);
        System.out.println(base1.opening(500));
        System.out.println(base1.deposit(22.22));
        System.out.println(base1.balance());

        DebitCard debit1 = new DebitCard(0,0,0);
        System.out.println(debit1.opening(400));
        System.out.println(debit1.deposit(33.33));
        System.out.println(debit1.balance());
        System.out.println(debit1.withdraw(33.33));
        System.out.println(debit1.balance());
    }
}

总结

在Java继承中,当子类需要修改父类的私有属性时,务必使用父类提供的 getter 和 setter 方法。直接在子类中声明同名变量不会修改父类的属性,而是创建了一个新的局部变量。 理解这一点对于编写正确的继承关系代码至关重要。

热门AI工具

更多
WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

VibeKnow
VibeKnow Hot

一款AI视频创作工具,主要用于全球首个AI知识视频创作平台,文档、文章、网页,一键生成视频,适合需要提升相关任务效率的用户。

超级麦吉

一款通过数字员工协作完成调研、数据分析与文档制作的AI办公平台。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

Flowith
Flowith Hot

Flowith是一款基于画布和智能体工作流的 AI 协作工作空间。

立刻MV
立刻MV Hot

立刻MV是一款AI文本写作工具,AI 音乐视频(MV)创作工具。

二狗PPT
二狗PPT Hot

一款AI演示文稿工具,主要用于专为中式职场打造的AI PPT生成工具,适合需要提升相关任务效率的用户。

火山引擎

火山引擎是一款面向企业的云计算与AI服务平台。

相关专题

更多
c++怎么把double转成int
c++怎么把double转成int

本专题整合了 c++ double相关教程,阅读专题下面的文章了解更多详细内容。

4688

2025.08.29

C++中int、float和double的区别
C++中int、float和double的区别

本专题整合了c++中int和double的区别,阅读专题下面的文章了解更多详细内容。

904

2025.10.23

Go-Zero API开发使用教程
Go-Zero API开发使用教程

本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

0

2026.11.12

Go-Zero安装与goctl环境配置教程
Go-Zero安装与goctl环境配置教程

本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。

0

2026.11.12

Go-Zero零基础入门教程
Go-Zero零基础入门教程

本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。

0

2026.11.12

Postman身份认证怎么配置
Postman身份认证怎么配置

本专题从实际API接口调试场景出发,讲解Postman身份认证的完整配置流程,包括常见认证协议介绍、授权参数设置、访问令牌填写、OAuth 2.0授权及认证失败排查,帮助用户正确完成接口授权与访问验证。

120

2026.11.06

Postman请求头Headers怎么设置
Postman请求头Headers怎么设置

围绕Postman HTTP请求头配置展开,讲解Headers选项的具体使用方式,包括Key和Value参数填写、请求头信息添加、常见Header字段设置及请求头修改方法,帮助用户解决接口调试过程中遇到的请求头配置问题。

80

2026.11.06

Postman接口请求发送教程
Postman接口请求发送教程

详细介绍Postman接口请求的创建与发送方法,涵盖GET和POST请求、URL配置、请求参数、Headers请求头、Body请求体设置以及响应结果查看,帮助用户掌握Postman接口请求的完整操作流程。

80

2026.11.06

DBeaver怎么导入数据
DBeaver怎么导入数据

DBeaver数据导入专题,整理Excel、CSV、SQL、TXT等常见文件的数据导入方法,涵盖目标数据库选择、数据表创建、字段映射、数据类型设置及导入参数配置等操作,帮助用户将本地文件中的数据写入数据库,并了解批量导入、重复数据处理和导入失败等常见问题的解决方法。

80

2026.11.05

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
dev.java 官方:Learn Java
dev.java 官方:Learn Java

共0课时 | 0人学习

Java JDBC数据库连接官方教程
Java JDBC数据库连接官方教程

共0课时 | 0人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn