如果没有调用其他方法,我将如何调用方法?

时间:2017-11-22 13:04:59

标签: java

我试图设置一个包含特定值的类,然后可以将其用作默认值。例如:

public class Account {
  private GUID;
  private balance;

  public Account(int balance) {
    this.balance = balance;
    this.GUID = new GUID();
  }

  public getBalance() {
    return this.balance;
  }

然后在使用过程中,我会以某种方式完成这项工作:

Account test = new Account(40);
System.out.println("Account balance: " + test);

那会返回:Account balance: 40

而不是写:

Account test = new Account(40);
System.out.println("Account balance: " + test.getBalance());

有没有办法在Java中执行此操作?

4 个答案:

答案 0 :(得分:4)

做这样的事情。

public class Account {
   private GUID guid;
   private int balannce;

 public Account(int balance) {
    this.balance = balance;
    this.guid = new GUID();
  }

  public getBalance() {
    return this.balance; 
  }      

  @Override
  public String toString() {
    return String.format("%03d", balance);
  }
}

答案 1 :(得分:1)

要实现您的要求,您需要覆盖类中的toString()方法,该方法继承自Object类(Java中的所有类都继承自Object类)。< / p>

您可以在方法代码中添加类似的内容:

public String toString() {
    return this.balance;
}

覆盖该方法后,当您调用System.out.println(test)时,您将在输出中看到从测试对象分配给balance字段的值。

答案 2 :(得分:0)

首先,你编写它的方式使它看起来像2.5类(或一个带有2个构造函数的类)而不是一个类似你想要的类。

要让课程按原样工作,请将课程更改为:

public class Account 
{
  private GUID; //Not sure if this needs a type or if GUID is the type!
  private double balance; //Added the double type, which holds a decimal

  public Account(int balance) //This is your constructor: no return type
  { 
    this.balance = balance;
    this.GUID = new GUID();
  }

  public double getBalance()  //Added return type for this method 
  {
    //Now it will return the number.
    return this.balance;
  }

  //Now to override the toString method for the class:
  public String toString()  //Notice this one returns String
  {
    return "Account balance: $" + this.balance.toString();
  }
}

因此,根据需要,您现在可以执行Account test = new Account(40);,它将根据您的类创建一个新对象,余额为40.您可以只提取数字并将其存储在变量中以进行操作或添加完成这样的操作:double theBalance = test.getBalance();如果您只是在对象上调用toString(),test.toString();它将返回Account balance: $40.0

的奇特输出

请注意,原始double可以有许多小数点的精度,因此您可能希望在toString函数中舍入这些值以使其漂亮。由于您将余额变量设为私有变量,因此您还需要创建一个&#34; setter&#34;在创建对象后更改平衡的功能,因为您当前只能在创建对象期间设置它。也许你可以在每次更新时都能获得价值,这样就不会有任何关于客户平衡的混淆?

希望这能够提供帮助,如果您仍有问题请发表评论! Java也是我的第一语言,在我完全理解对象之前它有点疯狂,但是一旦你将它们包裹在它们周围......令人惊讶的是,一切都变得简单。你现在正在学习它们很好

答案 3 :(得分:-4)

恐怕你不能这样做。

您可以为此定义toString()方法。 因为如果你直接打印对象(没有任何方法),那显然会打印该对象的地址,而不是它的变量的内部值。

所以是的,你不能那样做。

希望这可以帮助你。

相关问题