java中的方法重写举例?

来源:百度知道 编辑:UC知道 时间:2024/06/19 23:24:20
class People
{protected double weight,height;
public void speakHello()
{System.out.println("yayawawa");
}
public void averageHeight()
{heigth=173;
System.out.println("average height:"+height);
}
public void averageWeight()
{weight=70;
System.out.println("average weight:"+weight);
}
}
class ChinaPeople extends People
{代码1//重写public void speakHello()方法
//要求输出类似“你好,吃饭了吗”这样的汉语信息
代码2//重写public void averageHeight()方法
//要求输出类似“中国人的平均身高:173.0厘米”这样的汉语信息

代码3//重写public void averageWeight()方法
//要求输出类似“中国人的平均体重:67.34公斤”这样的汉语信息
System.out.println(ChinaPeople.speakHello+ChinaPeople.averageHeight+ChinaPeople.averageWeight);
public void chinaGongfu()
{System.out.println("坐如钟,站如松,睡如弓");
}
}
class AmericanPeople extends People
{代码5//重写public void speakHello()方法
//要求输

重写嘛。就是重写写你父类中的方法,和写普通方法没什么区别,就是在用这个类的时候分清楚是用子类和父类就可以了。代码1//重写public void speakHello()方法
//要求输出类似“你好,吃饭了吗”这样的汉语信息
就直接写public void speakHello(){System.out.println("你好,吃饭了吗");}这样就可以了,没什么特别的。

方法重写就是子类的方法覆盖了父类的方法,即子类的方法名和父类的方法名相同

class People

{
protected double weight,height;
public void speakHello()
{
System.out.println("yayawawa");
}
public void averageHeight()
{
height=173;

System.out.println("average height:"+height);
}
public void averageWeight()
{
weight=70;

System.out.println("average weight:"+weight);
}
}
class ChinaPeople extends People
{
//代码1//重写public void speakHello()方法
// 要求输出类似“你好,吃饭了吗”这样的汉语信息
public void speakHello()
{
System.out.println("你好,吃饭了吗");
}

//代码2//重写public void averageHeight()方法