zoukankan      html  css  js  c++  java
  • java this 子类调父类,父类再调用子类已覆盖的方法及属性(又一次理解)

    之前一直以为 this关键字 是指调用者对象,但是这次才真正理解,this代表当前对象,但是指向调用者对象,其实就是多态的用法,如下所示:B 继承了 A,在B 中调用A类的方法,在A 中用this 访问成员变量和方法,此时,如果用this访问成员变量,如下,this.s ,无论B 子类有没有 s属性,又或者s 的修饰符是 private 或者 public ,this.s 永远会打印出 当前类的 s属性值,原因:成员变量不能被重写,不能覆盖  ;再说,用this访问方法,如下所示: 在A 中 this.test() , 请注意,此时,this代表A 类,但是指向B ,如: A  a = new B() ;      因为 B 类 重写了父类的test方法,所以会调用B 的test 方法 ;       再如,将A 类的test方法改成 private类型的,此时 this.test()将调用A 类的 test方法,因为此时虽然B 类也有test方法,但是这个方法不是重写A类的方法,是一个自己独有的方法,因为父类是private私有的类型,子类不能拥有,敬礼!

    1. public class HelloA {  
    2.     public static void main(String[] args) {  
    3.      new B().print();  
    4.     }  
    5. }  
    1. class B extends A{  
    2.     private String s = "B" ;  
    3.     public void print() {  
    4.         super.print();  
    5.     }  
    6.     public String test(){  
    7.         return "test_B";  
    8.     }  
    9. }  
    1. class A {  
    2.     private String s = "A" ;  
    3.     public void print() {  
    4.         System.out.println(this.s);  
    5.         System.out.println( this.test());  
    6.     }  
    7.     public String test() {  
    8.         return "test_A";  
    9.     }  
    10. }  


    打印结果为:

       A
    test_B

       1,在B中调用A类的print方法,在A中 用this调用s属性和test方法,此时,this是 A对象,但是打印出了A中的属性,调用了 B 类的方法, 说明方法可以重写,属性不能重写

       2,如果把 A类的test方法改为private,则会调用A类的 test方法,原因是因为 B类中的test方法不是重写的A类的test方法,可以说是一个新的方法,因为A类的test方法是私有的

  • 相关阅读:
    ant 软件包不存在报错
    在 Internet Explorer 中使用 Windows 窗体控件
    智能客户端
    Back to the Future with Smart Clients
    "Automation 服务器不能创建对象" 的解决方案
    Top 10 Reasons for Developers to Create Smart Clients
    Updater Application Block for .NET
    Smart Client Application Model and the .NET Framework 1.1
    Security and Versioning Models in the Windows Forms Engine Help You Create and Deploy Smart Clients
    智能客户端技术总结(二)
  • 原文地址:https://www.cnblogs.com/kabi/p/8274778.html
Copyright © 2011-2022 走看看