Java 'this' syntax

I constantly run into this problem:


class MyClass implements MyInterface {
	
	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			// SecondClass class = new SecondClass(this);
			// I want to pass 'MyClass' as 'this' parameter.
			// Is it possible to achieve somehow?
		}
	};
}

class SecondClass {
	SecondClass(MyInterface interface) {
	}
}

Is there a proper way to handle this?

class MyClass implements MyInterface {
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            SecondClass class = new SecondClass(MyClass.this);
        }
    };
}

class SecondClass {
    SecondClass(MyInterface interface) {
    }
}

-ClaasJG

@Edit I failed the code tags

Well that was easy :smiley:

You have got a typo in there, variables can’t be named the same as a keyword ‘class’. Here’s the corrected code.


class MyClass implements MyInterface {
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            SecondClass klass = new SecondClass(MyClass.this);
        }
    };
}

class SecondClass {
    SecondClass(MyInterface i) {
    }
}

Neat solution from ClaasJG!

What I’ve done in the past was this:


class MyClass implements MyInterface {

    private final MyClass thisInstance = this;

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            SecondClass klass = new SecondClass(thisInstance);
        }
    };
}

class SecondClass {
    SecondClass(MyInterface i) {
    }
}

It seems to me that the possible benefit is that it’s the specific instance that is now passed. But if there are problems with what I’m doing, I’d be happy to hear about them! Off the top of my head, I can’t remember if the “final” modifier was requirered or not.

I don’t think the [icode]final[/icode] modifier is required if the variable is a class-scope variable.

Previously I used to use ‘dis’ variable to store this :smiley:

Instance variables do not need to be final to be used in anonymous inner classes.

[icode]MyClass.this[/icode] is the best and cleanest solution however.

mine was ‘thiz’ :wink:

I worked on a project with my uncle and he used to call it [quote]that
[/quote]