Question

Is it possible for a class itself to define a new class in OOP? Are there any languages (Lisp, etc.) that may allow this to happen? Is this something that can be done in OOP at all, or are there logical flaws in this concept (possibly something along the lines of the base "object" class being unable to redefine a new "object" class?)

For example; If class "B" is a subclass of superclass "A", could you theoretically code a catch block within "B" to create a new sibling class "C" of superclass "A" whenever a specific error is caught? Or would that be completely out of reach for conventional programming languages?

I did some reading regarding Lisp for the first time today, and the concept of editing the actual data structures within the language made me curious about this. Thanks.

Was it helpful?

Solution 2

Languages such as Javascript and Python treat functions and methods as objects, and by replacing those functions and methods a developer can dynamically modify an object and its behavior at runtime. This could be compared to "defining a new class", but in dynamically-typed (or duck-typed) languages this means very little.

In strongly-typed languages such as Java, a developer can create an "anonymous inner class" without a name but with a reference to final variables set in the scope.

abstract class CustomAdder {
  abstract int add(int datum);

  static CustomAdder createCustomAdder(final int numberToAdd) {
    return new CustomAdder() {
      @Override int add(int datum) {
        return numberToAdd + datum;
      }
    };
  }
}

// elsewhere
CustomAdder fiveAdder = CustomAdder.createCustomAdder(5);
fiveAdder.add(4); // returns 9
CustomAdder tenAdder = CustomAdder.createCustomAdder(10);
tenAdder.add(20); // returns 30

You could claim that an anonymous inner class is nothing more than a normal class missing a name, with some implicit constructor parameters, and you'd be right; in fact, these classes compile into separate numbered class files. Don't worry too much about that, though: One way or another, the code the program executes is code that some developer typed in that particular language, regardless of which file happens to contain it.

Of course, programs can also generate and dynamically compile/load code in assembly or computer languages, but I assume that's not what you mean. :)

OTHER TIPS

Sure, Common Lisp let's you create classes at runtime.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top