【问题标题】:Why can't I access the value of the class variable as the class variables are initialized at the time of object creation [duplicate]为什么我不能访问类变量的值,因为类变量是在创建对象时初始化的[重复]
【发布时间】:2021-02-13 17:56:33
【问题描述】:
class  Bill{
    int billid;
    // **setter for the variable**
    public void setbillid(int i){
        billid=i;
    }

    // **getter for the variable**
    public int getbillid(){
        return billid;
    }
}
public class Main{
    public static void main(String[] args) {
        // **This below is generating the error**  
        Bill b = new Bill();
        System.out.println(b.getbillid);
    }
}   

符号:变量 setbillid

位置:Bill 类型的变量 b

【问题讨论】:

  • b.getbillid 是一种方法,而不是变量。你的语法错误,应该是 b.getbillid()

标签: java compiler-errors compilation


【解决方案1】:

错误信息是错误的——应该是

符号:变量getbillid

而不是setbillid

:-)


您可以选择:

使用方法:System.out.println(b.getbillid());

或变量(不推荐):System.out.println(b.billid);
(假设它是可访问的)


无论如何,由于没有调用setter,它会有它的初始值:0\

我想建议使用通常的命名约定(getBillIdsetBillIdbillId、...)

【讨论】:

    【解决方案2】:
    System.out.println(b.getbillid());
    

    getbillid() 是一个返回Billid 的方法。调用方法的正确方式是objectName.methodName(),变量是objectName.variableName

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多