日期:2014-05-20  浏览次数:20624 次

和类同名的方法
class Animal
{
int height,weight;
Animal()
{
System.out.println("Animal construct");
}
void eat()
{
System.out.println("Animal eat");
}
void sleep()
{
System.out.println("Animal sleep");
}
void breathe()
{
System.out.println("Animal breathe");
}
}
class Fish extends Animal
{
int height;
Fish()
{
System.out.println("Fish construct");
}
void breathe()
{
System.out.println("Fish bubble");
}
}
class Integration
{
public static void main(String[] args)
{
Fish fh=new Fish();

}
}

我的问题是,为什么和类同名的方法执行,而不同名的方法不执行?是因为名字,还是因为void?

执行结果是:
Animal construct
Fish construct

------解决方案--------------------
同名的是构造函数,构造函数在对象创建时执行,执行初始化的功能。