我试图通过main函数调用我的对象。因为它需要静态参考,但我不知道怎么做。有人可以告诉我,我做错了什么?
private double checking;
private double saving;
public BankDisplay(double checking,double saving) // Constructor for subclass
{
checking=1000;
saving=1000;
}
public void setChecking(double checking){
this.checking=checking;
}
public double getChecking(){
return checking;
}
public void setSaving(double saving){
this.saving= saving;
}
public double getSaving(){
return saving;
}
BankDisplay checking1=new BankDisplay(checking, saving);
BankDisplay savings1= new BankDisplay(checking,saving);
当我尝试在main中打印对象checking1和saving1时,它显示"不能为静态函数提供非静态引用"。
答案 0 :(得分:1)
public BankDisplay(double checking,double saving) // Constructor for subclass
{
this.checking=checking;
this.saving=saving;
}
There is an error in constructor.
public static void main(String[] args){
BankingDisplay d1 = new BankingDisplay(100.15,200.15);
System.out.println(d1.getChecking());
}
答案 1 :(得分:1)
你的构造函数的方法是错误的,它应该是:
public BankDisplay(double checking,double saving) // Constructor for subclass
{
this.checking = checking;
this.saving = saving;
}
您的课程中也应该有一个toString()
功能,以便您正确打印对象。
如:
public String toString() {
return String.format("Checking: %s\nSavings: %s\n", this.checking, this.saving);
}
像这样使用:
System.out.println(checking1.toString());
答案 2 :(得分:0)
public class BankDisplay {
private double checking;
private double saving;
public BankDisplay(double checking,double saving) // Constructor for subclass
{
this.checking= checking;
this.saving= saving;
}
public void setChecking(double checking){
this.checking=checking;
}
public double getChecking(){
return checking;
}
public void setSaving(double saving){
this.saving= saving;
}
public double getSaving(){
return saving;
}
}
public class Main {
public static void main(String[]args){
BankDisplay account1 = new BankDisplay(1000,100);
System.out.println(account1.getChecking());
}
}
这应该可以解决您的问题:D您在构造函数中需要this
,因为您设置的是构造函数值,而不是您的私有变量。