Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the main class object from a function inside the class in Java? [duplicate]

Please read the 2 comments in the following code.

public class Field extends LinearLayout {
    public void init() {
        setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                // I want to access the main object 'Field' here(not the class, the object)
            }
        });

    // to be clear the object referred as 'this' from HERE should be accessed from where the above comment is.
    }
}

Is this possible? Is there a keyword to access the main class object from a function inside the object?

like image 391
SadeepDarshana Avatar asked Feb 14 '16 07:02

SadeepDarshana


People also ask

How do you call a main method from another method in Java?

Call a MethodInside main , call the myMethod() method: public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!"

How do you copy an object in Java?

Clone() method in Java. Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. In Java, there is no operator to create a copy of an object.


1 Answers

Yes, you should use Field.this to access the Field instance from within the anonymous class instance.

like image 56
Eran Avatar answered Oct 17 '22 14:10

Eran