问题遇到的现象和发生背景
有点不太理解这个Java变量我main方法运行完后 为什么改变了变量的值,下次运行的时候变量的缺省值是我上次赋值的常量;
我的疑问?
java中对变量的更改不是类加载的时赋值嘛,栈抛出时就没了的嘛**
用代码块功能插入代码,请勿粘贴截图
package _06抽象类案例_加油站收银系统;
//创建一个抽象卡类(Card),提供卡号(id),余额(balance),抽象的支付方法(pay)。
public abstract class Card {
private String id; //卡号
private double balance; //余额
public Card() {
}
public Card(String id, double balance) {
this.id = id;
this.balance = balance;
}
//抽象的支付方法(pay)。
//double money 加油的金额
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public final void pay(double money) {
System.out.println("支付成功");
System.out.println("原价:"+money);
double pay = discount(money);
System.out.println("折扣价:"+pay);
double newBalance = getBalance() - pay;
System.out.println("余额:"+newBalance);
//更新余额
setBalance(newBalance);
}
public abstract double discount(double Number);
}
//金卡
public class GoldenCard extends Card{
public GoldenCard(){}
public GoldenCard(String id, double balance){
super(id,balance);
}
//重写支付功能,按照原价的8折计算输出。
@Override
public double discount(double Number) {
return Number *0.8 ;
}
}
//银卡
public class SilverCard extends Card{
public SilverCard() {
}
public SilverCard(String id, double balance) {
super(id, balance);
}
//重写支付功能,按照原价的8.5折计算输出。
@Override
public double discount(double Number) {
return Number * 0.85;
}
}
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
GoldenCard g = new GoldenCard("vip001", 10000);
Scanner sc = new Scanner(System.in);
System.out.println("请输入支付金额:");
double money = sc.nextDouble();
g.pay(money);
System.out.println(g.getBalance());
}
}