Answer the question
In order to leave comments, you need to log in
Why is the context accessed through MainActivity.this?
Hello. I have repeatedly seen how the context is accessed through MainActivity. this
I know that the this keyword is used in java to call additional constructors inside other constructors and to specify fields when the names of the constructor parameters and class fields match.
I have read that there is another use of the this keyword, which is to get a reference to an outer class. Through Outer.this
or Outer.super (to get a reference to the parent of the outer class). I tried to do this in an imperial way. Get a link to the outer class and the child class in order to understand what the link will come to me, but I could not refer to either the outer class or the parent class using ClassName.this.
Look at the code
public class KeyWods {
public static void main(String[] args) {
C c = new C();
C.D d = new C().new D();
d.method();
B b = new B();
b.method();
}
}
class A {
@Override
public String toString() {
return "A";
}
}
class B extends A{
public void method(){
System.out.println(B.this.toString());
}
@Override
public String toString() {
return "B";
}
}
class C extends B{
class D {
public void method(){
System.out.println(D.this.toString());
}
@Override
public String toString() {
return "D";
}
}
@Override
public String toString() {
return "C";
}
}
Answer the question
In order to leave comments, you need to log in
This is the essence of inheritance. If class B inherits from A, then A is the parent of class B, and B is a descendant of A. Even if C inherits from B, it will not cease to be a descendant of class A, just for class B it will be a direct descendant.
If a method requires an object of the Context class, then any descendants of the Context class can be passed. And MainActivity is a child of Context, so it will do.
class C extends B{
class D {
public void method(){
System.out.println(C.this.toString()); // C.this - ссылка на внешний класс, т.е. на C
System.out.println(super.toString()); // super или D.super - ссылка на родительский класс,
// т.е. на Object, т.к. по умолчанию все классы наследуются от Object
}
@Override
public String toString() {
return "D";
}
}
@Override
public String toString() {
return "C";
}
}
The activity context and android as a property activity is needed for simple access from event handler class heirs ..
Instead of this, I like context.
In the constructor, a reference to itself is assigned.
And in oncreate, you can write handlers through anonymous classes.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question