Java 代码分析:座机和移动手机类的实现
这段代码定义了两个类 Telephone 和 MobilePhone,分别代表座机和移动手机。它们都有电话号码 (number) 和余额 (balance) 两个属性,以及通话 (call)、显示余额 (showBalance)、充话费 (recharge) 等方法。
Telephone 类
public class Telephone {
private String number; // 电话号码
private double balance; // 余额
public Telephone(String number, double balance) {
this.number = number;
this.balance = balance;
}
// 计算通话费用
public double call(double time) {
double price = 0.2; // 每分钟通话费用
double cost = time * price;
balance = balance - cost; // 计算余额
return cost;
}
// 显示余额
public void showBalance() {
System.out.println('当前余额为:' + balance);
}
// 充话费
public void recharge(double amount) {
balance = balance + amount;
System.out.println('充值成功!当前余额为:' + balance);
}
// 获取电话号码
public String getNumber() {
return number;
}
// 设置电话号码
public void setNumber(String number) {
this.number = number;
}
// 获取余额
public double getBalance() {
return balance;
}
// 设置余额
public void setBalance(double balance) {
this.balance = balance;
}
}
MobilePhone 类
public class MobilePhone {
private String number; // 电话号码
private double balance; // 余额
public MobilePhone(String number, double balance) {
this.number = number;
this.balance = balance;
}
// 计算通话费用
public double call(double time) {
double price = 0.3; // 每分钟通话费用
double cost = time * price;
balance = balance - cost; // 计算余额
return cost;
}
// 显示余额
public void showBalance() {
System.out.println('当前余额为:' + balance);
}
// 充话费
public void recharge(double amount) {
balance = balance + amount;
System.out.println('充值成功!当前余额为:' + balance);
}
// 获取电话号码
public String getNumber() {
return number;
}
// 设置电话号码
public void setNumber(String number) {
this.number = number;
}
// 获取余额
public double getBalance() {
return balance;
}
// 设置余额
public void setBalance(double balance) {
this.balance = balance;
}
}
Test 类
public class Test {
public static void main(String[] args) {
Telephone phone1 = new Telephone('010-12345678', 100); // 创建座机对象
MobilePhone phone2 = new MobilePhone('13812345678', 50); // 创建移动手机对象
double cost1 = phone1.call(3); // 座机通话费用
double cost2 = phone2.call(5); // 移动手机通话费用
System.out.println('座机通话费用为:' + cost1);
System.out.println('移动手机通话费用为:' + cost2);
phone1.showBalance(); // 显示座机余额
phone2.showBalance(); // 显示移动手机余额
phone1.recharge(50); // 座机充值
phone2.recharge(100); // 移动手机充值
}
}
在测试类 Test 中,创建了一个座机对象和一个移动手机对象,分别进行了通话、显示余额和充值等操作。
这段代码展示了如何使用 Java 类来模拟座机和移动手机,包括基本属性、通话、显示余额和充值等功能。通过代码分析,你可以了解面向对象编程的应用以及基本方法的实现。
原文地址: https://www.cveoy.top/t/topic/oBpK 著作权归作者所有。请勿转载和采集!