jcarsw04

Newbie
Jan 25, 2011
43
0
15
I noticed in the Android SDK documentation that the class Context is declared as an abstract class but I see pieces of code where Context objects exist. TextView's constructor, for example, takes a Context object as a parameter. I thought you couldn't create objects of classes that were declared as abstract. How is this possible? I'm pretty new to Android and Java in general.
 
You can create a pointer capable of pointing to an abstract class object, but you can't allocate memory for an abstract class using the new keyword. You cant say new Context(), for example, but you can assing a child of Context to a Context object (which is what Activities do).
 
An abstract class is like a template for how the class should look, however contains only a partial implementation (whereas an interface has no implementation)

The main purpose for interfaces and abstract classes is for type checking when passing arguments to functions for example.

Similar to an interface, if another class extends the abstract class then it provides an implementation for the abstract members so that the code can safely call all accessible members that are declared in the abstract class (or interface) knowing that they have to exist as they are specified in the abstract class.

So the code is no longer dependant on only one implementation of a class which increases its re-usability.

So as many classes in Android extend the abstract Context class they can be passed to any function which takes an argument of the type Context and the implementation for that function knows that any accessible members of the abstract Context have been implemented by the extending class.

Here is a link with more information about abstract classes

Abstract Methods and Classes (The Java