this和super的区别和应用 学习笔记

A:this和super都代表什么

  • this:代表当前对象的引用,谁来调用我,我就代表谁
  • super:代表当前对象父类的引用
    • B:this和super的使用区别
  • a:调用成员变量
    • this.成员变量 调用本类的成员变量,也可以调用父类的成员变量
    • super.成员变量 调用父类的成员变量
  • b:调用构造方法
    • this(...) 调用本类的构造方法
    • super(...) 调用父类的构造方法
  • c:调用成员方法
    • this.成员方法 调用本类的成员方法,也可以调用父类的方法
    • super.成员方法 调用父类的成员方法
class Fu{
            public int num = 10;
            public Fu(){
                System.out.println("fu");
            }
        }
        class Zi extends Fu{
            public int num = 20;
            public Zi(){
                System.out.println("zi");
            }
            public void show(){
                int num = 30;
                System.out.println(num);
                System.out.println(this.num);
                System.out.println(super.num);
            }
        }
        class Test1_Extends {
            public static void main(String[] args) {
                Zi z = new Zi();
                z.show();
            }
        }

猜你喜欢

转载自blog.51cto.com/357712148/2131478