[英]If I set up a class method with 2 parameters defined from the other class, how can I get the values defined on the other class?
say I declared a Camera
class 说我宣布了一个
Camera
类
public class Camera {
}
then I created another class 然后我创建了另一个类
public int compare (Camera camOne, Camera camTwo) {
}
If I set the value of camOne.price
, where price is a defined value in the Camera
class, how can I retrieve the value? 如果我设置
camOne.price
的值,其中price是Camera
类中的定义值,我该如何检索该值?
You could make it public: 您可以将其公开:
public int var
Or create getter and setter methods: 或者创建getter和setter方法:
public static int getVar ()
{
return var;
}
Most usually you would do one of two options: 通常,您会选择以下两种方法之一:
1. Least preferred: 1.最不喜欢的:
public class Camera {
public float price;
}
public class CameraComparer {
public float compare (Camera camOne, Camera camTwo) {
// do something; e.g. return difference
return camOne.price - camTwo.price;
}
}
2. More preferred/Standard: 2.更优选/标准:
public class Camera {
private float price;
public float getPrice() {
return price;
}
}
public class CameraComparer {
public float compare (Camera camOne, Camera camTwo) {
return camOne.getPrice() - camTwo.getPrice();
}
}
What are you trying to accomplish? 你想达到什么目的?
Is there a reason why you would prefer not to use a private access modifier, and a getter method. 是否有理由不使用私有访问修饰符和getter方法。 I would be concerned to make it public just because of ease of use, as it could cause issues down the road.
我会因为易于使用而将其公之于众,因为它可能会导致问题。
Based on the comments I have read it seems like you are trying to make a compare method, which is fairly common. 基于我已经阅读的评论,您似乎正在尝试制作比较方法,这是相当常见的。 Maybe another approach could be implementing the
Comparable
interface , and this would force you to implement the compareTo method. 也许另一种方法可能是实现
Comparable
接口 ,这将迫使您实现compareTo方法。
See the following code for an example: 有关示例,请参见以下代码:
package com.grade;
import java.util.Comparator;
public class Grade implements Comparable {
private double percentage;
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
@Override
public int compareTo(Object o1) {
if (o1 instanceof Grade) {
Grade grade1 = (Grade) o1;
if (this.getPercentage() > grade1.getPercentage()) {
return 1;
} else if (this.getPercentage() < grade1.getPercentage()) {
return -1;
} else {
return 0;
}
}
return -1;
}
@Override
public boolean equals(Object obj1) {
if (obj1 instanceof Grade) {
Grade grade1 = (Grade) obj1;
if (this.getPercentage() == grade1.getPercentage()) {
return true;
} else {
return false;
}
}
return false;
}
public static void main(String args[]) {
Grade chem = new Grade();
chem.setPercentage(92.50);
Grade astro = new Grade();
astro.setPercentage(40.12);
System.out.println(chem.compareTo(astro));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.