说我宣布了一个Camera
类
public class Camera {
}
然后我创建了另一个类
public int compare (Camera camOne, Camera camTwo) {
}
如果我设置camOne.price
的值,其中price是Camera
类中的定义值,我该如何检索该值?
答案 0 :(得分:0)
你可以公之于众:
public int var
或者创建getter和setter方法:
public static int getVar ()
{
return var;
}
答案 1 :(得分:0)
通常,您会选择以下两个选项之一:
<强> 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。更优先/标准:
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();
}
}
答案 2 :(得分:0)
你想要完成什么?
是否有理由不使用私有访问修饰符和getter方法。我会因为易于使用而将其公之于众,因为它可能会导致问题。
根据我所看到的评论,您似乎正在尝试制作比较方法,这是相当常见的。也许另一种方法可能是实现Comparable
interface,这会迫使你实现compareTo方法。
请参阅以下代码以获取示例:
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));
}
}