当前位置: 移动技术网 > IT编程>开发语言>Java > 区分Java的方法覆盖与变量覆盖

区分Java的方法覆盖与变量覆盖

2019年07月22日  | 移动技术网IT编程  | 我要评论

首先,我们看看关于重载,和覆盖(重写)的简明定义:

方法重载:如果有两个方法的方法名相同,但参数不一致,哪么可以说一个方法是另一个方法的重载。

方法覆盖:如果在子类中定义一个方法,其名称、返回类型及参数签名正好与父类中某个方法的名称、返回类型及参数签名相匹配,那么可以说,子类的方法覆盖了父类的方法

我们重点说说覆盖问题,以如下代码为例:

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 
 
 } 

上述结果说明: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 
 
 } 

通过运行结果我发现:变量的覆盖实际上与方法的不尽相同。

用我自己的话说:变量的覆盖最多只能算是半吊子的覆盖。

要不然,向上转换与不会发生数据丢失现象

people pp=new student(); 
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; 
 } 
} 
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 
 
 } 

显然,如此的覆盖,才是对我们更有用的覆盖,因为这样才能达到:把具体对象抽象为一般对象的目的,实同多态性

以上只是我个人的看法,有不对的地方欢迎指出来讨论。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网