-3

When I do this:

 baseApp = (MyApp)this.getContext();

What am I actually doing?

as opposed to doing:

 baseApp = myApp.doSomething();

I'm not concern with the methods but understanding the construction. How are those 2 above different and why?

Whats the meaning of doing (MyApp)?

sirvon
  • 2,547
  • 1
  • 31
  • 55

2 Answers2

2

Whats the meaning of doing (MyApp)?

It is a reference type cast.

It checks that the reference produced by evaluating the RHS (i.e. this.getContext() ) is compatible with MyApp and then uses it that as the result of the expression (with that type). If the reference given by the RHS expression is not for a compatible type, a runtime exception will be thrown.

By contrast ...

  baseApp = myApp.doSomething();

is just calling the doSomething() method and assigning it ... WITHOUT doing a typecast. If the doSomething() method does not deliver a value of the correct type, you will get a compilation error.


For the record, there is no "instantiation" going on here. Instantiation is done using the new operator1.

1 - ... or by calling specific reflective methods.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

Firstly where are you calling this from? An Activity?

The first line is casting the current objects context to a MyApp object then assigning it to an object named baseApp. And I also assume baseApp is of type MyApp.

The second line is assigning the value returned from the method named doSomething() to baseApp


but more information is needed to compare further.

string.Empty
  • 10,393
  • 4
  • 39
  • 67