Skip to content

Instantly share code, notes, and snippets.

@shaikhul
Created January 17, 2018 03:43
Show Gist options
  • Save shaikhul/d3df7bef7130e3992c52494269bed445 to your computer and use it in GitHub Desktop.
Save shaikhul/d3df7bef7130e3992c52494269bed445 to your computer and use it in GitHub Desktop.
Java Context/this in action
/**
Run it at https://repl.it/repls/PunyDisguisedDalmatian
*/
class Foo {
public void helloFoo() {
System.out.println("Hello Foo");
}
public Foo getContext() {
return this;
}
public Foo getContextByClassName() {
return Foo.this;
}
}
class Main {
public static void main(String[] args) {
Foo foo = new Foo();
// calling instance method using foo object
foo.helloFoo();
// get foo context via the object
Foo context = foo.getContext();
context.helloFoo();
// now get it using getContextByClassName
context = foo.getContextByClassName();
context.helloFoo();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment