abstract classes

Douglas Edric Stanley


I saw Stéphane Cousot on my way to the atelier this morning and he suggested I use abstract classes instead of inheritance for my experiments. This too is a concept I know pretty well from other languages, but haven’t really used in Java yet. As it turns out, it’s pretty easy.

Abstract classes are classes that cannot be instantiated. I.e. you can’t turn an abstract class into an object directly. It’s sorta-kinda like a half-finished prefab house: parts of it are already built, but you still have to lay down your own foundation. In my example from yeasterday, the Animation class could have easily been an abstract class, since it was never transformed directly into an object: there was no Animation myAnimation = new Animation();, only Animation myAnimation = new Opening();, or Animation myAnimation = new Middle();.

To actually write an abstract class you just add the word abstract in the class declaration, as well as in the methods that you know will need to be added by the class that inherits it:

abstract class Animation {

  // this is a provided method that will work without creating
  // a new method inside of the subclass. it is not abstract:
  // as you can see it actually contains working code

  void setup() {

  // this is absolutely necessary and is incomplete by design
  // meaning that the object that inherits this abstract class
  // will absolutely positively have to create its own draw()
  // method, or else the java compiler will yell at you

  abstract void draw();


If you try to create a concrete object out of your abstract class (Animation), the compiler will yell at you: Semantic Error: Attempt to instantiate an abstract class "Temporary_983_7080$Animation". But you can very well tell it to create a new object out of a class that inherits from your abstract class:

void keyPressed() {

  switch(key) {

  case 'a':
    sketch = new SketchA();

  case 'b':
    sketch = new SketchB();