【问题标题】:How to use only certain class object values in java?如何在java中只使用某些类对象值?
【发布时间】:2019-02-10 20:25:36
【问题描述】:

我还在学习 java 并且发现它非常困难,而且我已经被这个困住了一段时间。

假设你有一个类,它的构造函数有点像这样:

public Fruit(String Name, String Type, double Price, int Stock) {
    this.Name = Name;
    this.Type = Type;
    this.Price = Price;
    this.Stock = Stock;
}

并说我们从中得到了这个对象,例如:

Fruit fruit1 = new Fruit("Apple", "Apple", "0.45", 23);

有了这些信息,我想编写一个用户可以输入然后订购食物的函数。如何使用此类对象中的信息在函数中使用?

【问题讨论】:

  • 提示:请阅读 java 命名约定。字段名和参数采用驼峰式,只有类名以大写开头。
  • 我假设您的函数将在 Fruit 类中。在这种情况下,您只需按照构造函数中演示的相同方式访问这些值,方法是在要使用的值前面添加this.。如果传入“数量”参数,只需将其乘以 this.Price 并返回成本。

标签: java function class oop


【解决方案1】:

通过稍后简单地读回这些字段,可能直接,或者使用您添加的 getter 方法,例如:

if (someFruit.getName().equals(theNameOfSomeFoodOrderedByCustomer)) {
  System.out.println("you ordered " + someFruit.getName() + " that will cost you " + someFruit.getPrice());  

从那时起,您可能想进一步研究 java getter/setter 方法,以查看相关示例。

【讨论】:

    【解决方案2】:

    要访问您的对象之一的非私有成员变量,请使用. 符号,如下所示:

    Fruit apple = new Fruit("Apple", "Apple", "0.45", 23);
    System.out.println(apple.price); //prints the price of the apple
    

    但是,在大多数情况下,为了封装,建议您使用 getter 和 setter 方法。通过这种方式,您可以更好地控制对象变量的访问方式。看看下面的例子:

    private int price;  //a private member variable
    
    //...
    
    public int getPrice() {return this.price} //example of a getter method
    public void setPrice(int nPrice) {this.price = nPrice;} //example of a setter method
    

    在上面的示例中,您将无法直接在其类之外访问变量price。相反,您必须从 Fruit 的实例调用方法 getPrice()

    注意:最好以小写字母开头的变量名。

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 2016-03-20
      • 2011-08-11
      • 1970-01-01
      • 2015-08-02
      相关资源
      最近更新 更多