I’m trying to write a factory method in an abstract class in Java (so I want it to return a new instance of the extending class, rather than the super-class).
In PHP I’d do this using the self keyword:
abstract class Superclass {
public static function factory($arg) {
return new self($arg);
}
private function __construct($arg) {}
abstract public function doSomething() {}
}
Does Java have a keyword like self I can use for this?
No; in Java, static methods are not inherited in the same way as non-static methods are. A subclass will have the static methods of its superclass, but when they execute, they will execute in context of the superclass – so there is no keyword that can be used in static methods to find out what class the method was invoked through.
Edit: A more precise formulation is that static methods are not inherited at all; however, the language allows us to use
Subclass.foo()to call the static methodSuperclass.foo().Based on what you seem to want to achieve, you might want to implement the Abstract Factory pattern. It goes approximately like this:
Now, you can e.g. create a method that takes an
AbstractFactory(which, in reality, will be either aFactoryAor aFactoryB). CallingCreate()on this object will produce either aSubclassAor aSubclassB.Edit: Fixed compilation error (forgot to make the factories extend
AbstractFactory).