I am trying to create a static method that would return an instance of the class, something like:
class A {
public static A getInstance() {
return new A();
}
}
The problem I am having is that if I have a subclass B derived from A, I would like B.getInstance() to return an instance of B, and not A. In PHP world, you could use a keyword "self" to reference to your own type, so your getInstance() would look like:
public static function getInstance() {
return new self();
}
What's the best way to go about this?
By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.
You cannot have static and nonstatic member functions with the same names and the same number and type of arguments. Like static data members, you may access a static member function f() of a class A without using an object of class A .
A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class. Syntax: static class Class_Name { // static data members // static method }
The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.
You can't, basically. If a call to a static member which is only declared in a base class is actually expressed in terms of the derived class, like this:
// Urgh
Encoding ascii = ASCIIEncoding.ASCII;
// Worse yet (and yes, I've seen this)
Encoding ascii = UTF8Encoding.ASCII;
then the compiler silently transforms that to:
Encoding ascii = Encoding.ASCII;
The fact that the original source contained the name of a derived class is not preserved in the compiled code, so it can't be acted on at execution time.
How about using generics to provide the type to produce:
public static T getInstance<T>() where T : A, new()
{
return new T();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With