2016-04-20 57 views
-3
public boolean isAfraidOf(Animal animal) { 
    //Compare the class of this animal to Bird 
    if (animal.getClass() == Bird.class) { 
     return false; 
    } else { 
     return true; 
    } 

动物是超级类,鸟是子类,我需要知道他们比较两个类的区别吗?并提前致谢这意味着两个相同的类是什么意思?

+0

这意味着'动物'是'鸟'的一个实例,而不是一个子类。 – shmosel

+0

'return animal.getClass()!= Bird.class;'更容易。 –

+0

@shmosel谢谢你的回答,但也许我不能解释它的权利,我给了这部分代码作为例子..在我的代码我有3类动物,鸟和猫动物是超类,其他人是子类,但我只需要知道(一般情况下)当我必须比较两个类别彼此什么是我比较真正的事情,如果我有2个数字,所以我需要知道他们哪个更小..在这里我无法理解比较两个类的想法 –

回答

0

getClass()返回Class。所以animal.getClass()将返回类型动物和比较将返回false

因此,这里是你的理解的综合研究:

Animal animal = new Animal(); 

Bird bird = new Bird(); 

Animal birdAnimal = new Bird(); 

if (animal.getClass() == bird.getClass()){ 
    System.out.println("Bird equals to animal"); 
}else{ 
    System.out.println("Bird not equals to animal"); 
} 

if (birdAnimal.getClass() == animal.getClass()){ 
    System.out.println("BirdAnimal equals to animal"); 
}else { 
    System.out.println("BirdAnimal not equals to animal"); 
} 

if (animal.getClass() == Animal.class){ 
    System.out.println("animal equals to Animal"); 
}else{ 
    System.out.println("animal not equals to Animal"); 
} 

if (animal.getClass() == Bird.class){ 
    System.out.println("animal equals to Bird"); 
}else{ 
    System.out.println("animal not equals to Bird"); 
} 

这里是输出:

Bird not equals to animal 
BirdAnimal not equals to animal 
animal equals to Animal 
animal not equals to Bird 
+0

请注意,'animal.getClass()'返回'Class <?扩展动物>',而不是'类'。它不一定*返回“类型动物”,因为它可能是一个子类。 –

+0

@AndyTurner是的,但它返回等于。粘贴原始测试结果。 –

+1

非常感谢你:) –

0

如果我正确地理解你的问题,你要确定一个Animal是的类型Bird。要做到这一点,最简单的方法是使用instanceof举例:

if (animal instanceof Bird) { 
    return false; 
} else { 
    return true; 
} 

还有另一种方式做这样的事情虽然。在Java中,所有类默认都是Object。这意味着他们带有内置的.equals()方法。但是,如果您创建了动物和鸟类,则极有可能.equals()方法不足。当您创建一个新班级时,您应该重写.equals()方法以完全按照您的期望方式比较对象。例如,如果所有的动物都有体重,那么您可能需要比较一下。或不。也许你只想根据另一个属性来确定相等性。

+0

感谢您的回答..但无论这个代码,我需要知道一般情况下,当你比较两个类别彼此真正的东西你在他们比较,就像我比较两个数字,我会发现其中一个比另一个大,但我不知道我应该在两个班中比较哪些东西? –

+0

@ RehAmEL-Gamal你问的是如何比较Class类的对象吗? (例如'animal.getClass()== Bird.class')或类如何进行比较? –

+0

如何比较一般类。 –