【IT168 技术】首先,我们看看关于重载,和覆盖(重写)的简明定义:
方法重载:如果有两个方法的方法名相同,但参数不一致,哪么可以说一个方法是另一个方法的重载。
方法覆盖:如果在子类中定义一个方法,其名称、返回类型及参数签名正好与父类中某个方法的名称、返回类型及参数签名相匹配,那么可以说,子类的方法覆盖了父类的方法。
我们重点说说覆盖问题,以如下代码为例:
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
}
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
}
上述结果说明: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
}
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
}
通过运行结果我发现:变量的覆盖实际上与方法的不尽相同。
用我自己的话说:变量的覆盖最多只能算是半吊子的覆盖。
要不然,向上转换与不会发生数据丢失现象。
People pp=new Student();
System.out.println(pp.name);//运行结果为people
System.out.println(pp.name);//运行结果为people
就我个人的经验来说:变量的覆盖很容易让人犯错误.让人感觉又回到了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;
}
}
protected String name="people";
public String getName() {
return name;
}
}
public class Student extends People {
protected String name="student";
public String getName() {
return name;
}
}
显然,如此的覆盖,才是对我们更有用的覆盖,因为这样才能达到:把具体对象抽象为一般对象的目的,实同多态性。
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
}
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
}
以上只是我个人的看法,有不对的地方欢迎指出来讨论。