Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to use keyword "this" to call my enclosing methods or variables

I have a doubt if I have a non-static nested class why do I need to use the keyword "this" to call a method or variable of my enclosing class? What I think is the following: if a non-static nested class can access to methods and variables of its enclosing class and a non-static nested object instance is already associated to its enclosing object instance why do I need to use "this"? For example I have the following code:

public class ClassA {

    public class ClassB {

        public void bye() {
            ClassA.this.hello();
            // Why not just ClassA.hello()?
        }
    }

    public void hello() {

    }
}

and if from a method of my enclosing class I want to call a method of one of mine non-static classes how should I do?For example if from my method hello() I want to call bye() how should I type?

like image 635
zer0uno Avatar asked Nov 22 '25 15:11

zer0uno


1 Answers

First of all, you can simply call hello().

ClassA.hello() would look for a static method named hello() in ClassA. ClassA.this.hello() looks for an instance method.

like image 174
JB Nizet Avatar answered Nov 24 '25 03:11

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!