Is there a way to change the class that is being built in the constructor?
public class A { A() { //if (condition) return object of type B //else return A itself } } public class B extends A { }
Basically, I want to use the base class constructor as a factory method. Is this possible in java?
No, you have to use the factory method for Aif you want to do this. The client of your class has the right to expect that if it executes new A(), it will receive a class object A, and no other.
A
new A()
No, constructors only need to instantiate the class object that they represent. This is why there is no return value in the constructor.
, :
public class A { private A(){ } public static A getInstance(){ if (condition) return new B(); else return new A(); } } class B extends A { }
When the constructor code is called, the object is already created - you only initialize its fields. So it's too late to modify the class of an object.
You can try using reflection to create a subclass. However, this is a bad idea because the class does not need to know about its subclasses.
Using the factory method is the best approach in your case.
Source: https://habr.com/ru/post/1718973/More articles:Cloud 3D Clouds - tagsRails hard coding codes - ruby-on-railsIs it possible to find silence in audio files using Javascript? - javascriptWhat is a proxy class - c #Running a task every hour per hour with the App Engine cron API - pythonhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1718974/access-to-private-collection-fields-in-java&usg=ALkJrhjC2oOWuqVTmvREAIwzFRyzfv3krQHow easy is it to extend / change the Zend Framework? - phpHow can I programmatically trigger Google Analytics events without a browser? - javahttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1718977/using-yahoo-pipes-to-convert-an-rss-feed-into-ical&usg=ALkJrhggFOd531wZUx2zalFGD2TjW9O2PQZipFile inside ZipFile - javaAll Articles