重载:可以理解为旧的词语被赋予新的内容,然后根据语境判断其真实含义;
例子:
小明的妈妈:小明去擦玻璃!
小明: 我擦!
在这个例子中”我擦“可以根据语境的不同的,而有了不同的含义;
在java和c++中,构造器就是重载典型;根据传入参数的不同,创造不同的对象。
public class Tree {
int height;
Tree(){
System.out.println("Planting a seeding");
height=0;
}
Tree(int height) {
this.height = height;
System.out.println("Tree:"+height);
}
void info(){
System.out.println("无参info");
}
void info(int data){
System.out.println("有参info");
}
}
区分重载的方法:就是根据参数列表不同区分(甚至参数顺序可以区分)
void info(){
System.out.println("无参info");
}
void info(int data){
System.out.println("有参info");
}
void info(int data,int index){
System.out.println("有参info"+data+":"+index);
}
重载和返回值无关
因为在一个对象中,如果根据返回区分,那么使用对象调用时,怎么实现 对象.方法() 来调用相应的方法
void info(){
System.out.println("无参info");
}
int info(){
System.out.println("有参info");
}
tree.info();
重写:子类实现父类的同名方法, 并且参数的类型和个数完全相同
重写的标识符:@Override
class woody{
public void growth(int data){
System.out.println("woody:"+data);
}
}
public class Tree extends woody{
@Override
public void growth(int data) {
System.out.println("Tree:"+data);
}
}
重写和重载的区别:
区别 | 重写 | 重载 |
---|---|---|
返回值 | 返回值一般情况下和父类同名函数一致 | 对返回值无所谓 |
参数列表 | 相同 | (个数、类型)不相同 |
所在位置 | 在子类中 | 同一个类中 |
权限要求 | 重写方法不能小于父类中的方法 | 无要求 |