Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中仅使用某些类对象值?_Java_Function_Class_Oop - Fatal编程技术网

如何在java中仅使用某些类对象值?

如何在java中仅使用某些类对象值?,java,function,class,oop,Java,Function,Class,Oop,我仍在学习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 F

我仍在学习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);

有了这些信息,我想写一个函数,用户可以输入这个函数,然后点餐。如何使用该类对象中的信息在函数中使用

稍后只需直接读回这些字段,或者使用您添加的getter方法,如:

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

从这一点上讲,您可能需要进一步研究java getter/setter方法,以查看相关示例。

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

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()


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

提示:请阅读java命名约定。字段名和参数都是大写的,只有类名以大写开头。我假设您的函数应该在Fruit类中。在这种情况下,您只需通过在要使用的值前面添加
this.
,以与构造函数中演示的相同方式访问这些值。如果您传入一个“quantity”参数,只需将其乘以
this.Price
,然后返回成本。