java this和super

1、引用变量

this代表该类的对象,可以引用该类的实例变量、静态变量和方法。

super可以引用父类的实例变量、静态变量和方法。

this和super可以在类中任何地方使用调用变量方法,除了含静态块的区域不用使用this和super。

1.1 this

// Program to illustrate this keyword 
// is used to refer current class
class RR {
    // instance variable
    int a = 10;
 
    // static variable
    static int b = 20;
 
    void GFG()
    {
        // referring current class(i.e, class RR) 
        // instance variable(i.e, a)
        this.a = 100;
 
        System.out.println(a);
 
        // referring current class(i.e, class RR) 
        // static variable(i.e, b)
        this.b = 600;
 
        System.out.println(b);
    }
 
    public static void main(String[] args)
    {
        // Uncomment this and see here you get 
        // Compile Time Error since cannot use 
        // 'this' in static context.
        // this.a = 700;
        new RR().GFG();
    }
}

output:

100
600

1.2 super

// Program to illustrate super keyword 
// refers super-class instance
 
class Parent {
    // instance variable
    int a = 10;
 
    // static variable
    static int b = 20;
}
 
class Base extends Parent {
    void rr()
    {
        // referring parent class(i.e, class Parent)
        // instance variable(i.e, a)
        System.out.println(super.a);
 
        // referring parent class(i.e, class Parent)
        // static variable(i.e, b)
        System.out.println(super.b);
    }
 
    public static void main(String[] args)
    {
        // Uncomment this and see here you get 
        // Compile Time Error since cannot use 'super' 
        // in static context.
        // super.a = 700;
        new Base().rr();
    }
}

output:

10
20

2、构造函数

this()调用该类的构造函数。

super()调用父类的构造函数。

一般情况下,如果构造函数中没有super(),那么会默认调用父类的无参构造函数,相当于该构造函数的第一行隐含了super()语句。

this()和super()只能出现在构造函数的第一行,且不能同时出现this()和super()。因为同时出现,相当于初始化了对象两次,这是不允许的。

编译器也不允许通过this()来循环调用构造函数。

参考:

https://www.geeksforgeeks.org/difference-super-java/

https://www.geeksforgeeks.org/super-and-this-keywords-in-java/

猜你喜欢

转载自blog.csdn.net/jdbdh/article/details/81564268
今日推荐