大家好,新年快乐。
我刚来Java。我写了一个代码如下。当我运行它时,我得到以下输出。
1和2相同
1和2相等
为什么我不能为其他if语句获得相同的输出呢?所有3个对象(example1,example2和example3)都派生自类'test'。所有3个都来自相同的来源,类'test'。所以不仅1vs 2,而且1 vs 3和2 vs 3都应该相同/相等。
有什么好主意吗?
我的代码在这里:
公开课测试{public static void main(String[] args) {
Test example1 = new Test();
Test example2 = example1;
Test example3=new Test();
if (example1==example2){
System.out.println("1 and 2 are same");
}
if (example1==example3){
System.out.println("1 and 3 are same");
}
if (example2==example3){
System.out.println("2 and 3 are same");
}
if (example1.equals(example2)){
System.out.println("1 and 2 are equal");
}
if (example1.equals(example3)){
System.out.println("1 and 3 are equal");
}
if (example2.equals(example3)){
System.out.println("2 and 3 are equal");
}
}