首先,我们看看关于重载,和覆盖(重写)的简明定义:
方法重载:如果有两个方法的方法名相同,但参数不一致,哪么可以说一个方法是另一个方法的重载。
方法覆盖:如果在子类中定义一个方法,其名称、返回类型及参数签名正好与父类中某个方法的名称、返回类型及参数签名相匹配,那么可以说,子类的方法覆盖了父类的方法
我们重点说说覆盖问题,以如下代码为例:
public class People {
public String getName() {
return "people";
}
}
public class Student extends People {
public String getName() {
return "student";
}
}
public static void main(String[] args) {
People p=new People();
System.out.println(p.getName());//运行结果为people
Student s=new Student();
System.out.println(s.getName());//运行结果为student
People pp=new Student();
System.out.println(pp.getName());//运行结果为student
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
上述结果说明:student类的getName方法成功覆盖了父类的方法
我们再来看看变量的覆盖:
public class People {
protected String name="people";
}
public class Student extends People {
protected String name="student";
}
public static void main(String[] args) {
People p=new People();
System.out.println(p.name);//运行结果为people
Student s=new Student();
System.out.println(s.name);//运行结果为student
People pp=new Student();
System.out.println(pp.name);//运行结果为people
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
通过运行结果我发现:变量的覆盖实际上与方法的不尽相同。
用我自己的话说:变量的覆盖最多只能算是半吊子的覆盖。
要不然,向上转换与不会发生数据丢失现象
People pp=new Student();
System.out.println(pp.name);//运行结果为people
- 1.
- 2.
就我个人的经验来说:变量的覆盖很容易让人犯错误.让人感觉又回到了C++的继承[这里不是指C++带virtual的继承]
***我们再来看一段代码:
public class People {
protected String name="people";
public String getName() {
return name;
}
}
public class Student extends People {
protected String name="student";
public String getName() {
return name;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
main(String[] args) {
People p=new People();
System.out.println(p.getName());//运行结果为people
Student s=new Student();
System.out.println(s.getName());//运行结果为student
People pp=new Student();
System.out.println(pp.getName());//运行结果为student
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
显然,如此的覆盖,才是对我们更有用的覆盖,因为这样才能达到:把具体对象抽象为一般对象的目的,实同多态性
以上只是我个人的看法,有不对的地方欢迎指出来讨论。
原文链接:http://blog.csdn.net/kuangxiang_panpan/article/details/7443046
【编辑推荐】