1. Are you ready for the Galaxy S20? Here is everything we know so far!

Abstract Classes

Discussion in 'Android Development' started by jcarsw04, Sep 2, 2011.

  1. jcarsw04

    jcarsw04 Newbie
    Thread Starter

    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.

    1. Download the Forums for Android™ app!


  2. jonbonazza

    jonbonazza Android Expert

    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).
  3. ninjalizard

    ninjalizard Lurker

    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

Share This Page