Java - 调用超类的构造函数失败
Java - Calling the constructor of a superclass fails
这是我设置的基本 class 计算股票收益的方法。
在此处关注 "Stock" 构造函数:
public class Stock{
private String symbol;
private int totalShares;
private double totalCost;
public void Stock(String symbol){
this.symbol = symbol;
totalShares = 0;
totalCost = 0.0;
}
public double getProfit(double currentPrice){
double marketValue = totalShares * currentPrice;
return marketValue - totalCost;
}
public void purchase(int shares, double pricePerShare){
totalShares += shares;
totalCost += shares*pricePerShare;
}
public int getTotalShares(){
return totalShares;
}
}
我创建了一个名为 DividendStock 的子class,它应该计算股息收益。
public class DividendStock extends Stock{
private double dividends;
public DividendStock(String symbol){
super(symbol);
dividends = 0.0;
}
public void payDividend(double amountPerShare){
dividends += amountPerShare*getTotalShares();
}
}
这个class的构造函数不允许我调用superclass的构造函数:super(symbol);
报错信息如下:"constructor Stock in class Stock cannot be applied to given types;"
我已经搜索了解决方案,但似乎一切都已到位。
为什么它不允许我调用这个构造函数的任何想法?
构造函数没有任何 return 类型。当你输入 return 类型时,它将是一个普通的方法。
public void Stock(String symbol) {
this.symbol = symbol;
totalShares = 0;
totalCost = 0.0;
}
应该是
public Stock(String symbol) {
this.symbol = symbol;
totalShares = 0;
totalCost = 0.0;
}
替换它public void Stock(String symbol){ this.symbol = symbol; totalShares = 0; totalCost = 0.0; }
到public Stock(String symbol){ this.symbol = symbol; totalShares = 0; totalCost = 0.0; }
这是我设置的基本 class 计算股票收益的方法。 在此处关注 "Stock" 构造函数:
public class Stock{
private String symbol;
private int totalShares;
private double totalCost;
public void Stock(String symbol){
this.symbol = symbol;
totalShares = 0;
totalCost = 0.0;
}
public double getProfit(double currentPrice){
double marketValue = totalShares * currentPrice;
return marketValue - totalCost;
}
public void purchase(int shares, double pricePerShare){
totalShares += shares;
totalCost += shares*pricePerShare;
}
public int getTotalShares(){
return totalShares;
}
}
我创建了一个名为 DividendStock 的子class,它应该计算股息收益。
public class DividendStock extends Stock{
private double dividends;
public DividendStock(String symbol){
super(symbol);
dividends = 0.0;
}
public void payDividend(double amountPerShare){
dividends += amountPerShare*getTotalShares();
}
}
这个class的构造函数不允许我调用superclass的构造函数:super(symbol); 报错信息如下:"constructor Stock in class Stock cannot be applied to given types;"
我已经搜索了解决方案,但似乎一切都已到位。 为什么它不允许我调用这个构造函数的任何想法?
构造函数没有任何 return 类型。当你输入 return 类型时,它将是一个普通的方法。
public void Stock(String symbol) {
this.symbol = symbol;
totalShares = 0;
totalCost = 0.0;
}
应该是
public Stock(String symbol) {
this.symbol = symbol;
totalShares = 0;
totalCost = 0.0;
}
替换它public void Stock(String symbol){ this.symbol = symbol; totalShares = 0; totalCost = 0.0; }
到public Stock(String symbol){ this.symbol = symbol; totalShares = 0; totalCost = 0.0; }