您的位置:首页 > 编程语言 > Java开发

Java 中方法的重写,重载与覆盖的关系

2017-04-08 16:54 399 查看

学习记录04.08:Java 中方法的重写,重载与覆盖的关系

重写:即函数(方法)体的重写,方法名、参数、返回值类型不变,只改变方法内部算法。通常在子类父类之间。

重载:即函数的返回值和方法名相同,参数列表不同。通常用于某一类内部

覆盖:重写的另一种叫法。

下面我根据自己的理解写的例子:

//定义一个Animal抽象类
package demo0408;

abstract class Animal {
public String food;
public String name;

abstract void eat();

public void run() {
System.out.println(this.name + "跑动起来了");
}
}


package demo0408;

public class Dog extends Animal {
public Dog(String food) {
this.name = "Dog";
this.food = food;
}

// 重写Animal类中的eat方法
public void eat() {
System.out.println(this.name + "吃" + food);
}
//重载run方法
public void run(int speed) {
if(speed>100)
System.out.println(this.name + "快速的跑动起来");
else
System.out.println(this.name + "慢慢的跑动起来");
}
}


另一个关于重载的例子:

package demo0408;

public class demo {
class GetArea{
//计算圆的面积
public float getArea(float r){
float s;
s = 3.14f * r * r;
return s;
}
//计算长方形面积
public float getArea(float l,float w){
float s;
s = l * w;
return s;
}
//计算梯形面积
public float getArea(float a,float b,float h){
float s;
s = (a + b) * h / 2;
return s;
}
}
public static void main(String[] args){
demo d = new demo();
GetArea ga = d.new GetArea();
float s;
s = ga.getArea(1.0f);
System.out.println("半径为1的圆的面积为" + s);
s = ga.getArea(1.0f,2.0f);
System.out.println("长为2宽为1的长方形面积为" + s);
s = ga.getArea(1.0f,2.0f,2.0f);
System.out.println("上底位1下底为2高位2的梯形面积为" + s);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 学习记录