Can you instantiate a different object from the Constructor ? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 3

Can you instantiate a different object from the Constructor ?

Instead of an instance of this calss, can you create an instance of another class? A subclass, or any other class? I'm interested if its possible not for the practicability of it ..

3rd Nov 2016, 11:08 PM
Eduard Alexandru
Eduard Alexandru - avatar
2 ответов
+ 5
I'm not sure if I'm reading this right... Are you asking if you can instantiate an object inside a constructor? A class can have an object as one of its properties, but it can be instantiated without the constructor.
4th Nov 2016, 12:20 AM
Tamra
Tamra - avatar
+ 2
No. You get an obiect with new MyClass() and the constructor creates the obiect. Is it possible to make the constructor create an instance of a subclass or superclass of MyClass? In essence I wonder if the code new MyClass() can create an instance of a different class then MyClass() maybe a subclass or parent class of it and if I can decide in the constructor which class I want to create an instance of, since the constructor is the one that creates the instance.
4th Nov 2016, 12:29 AM
Eduard Alexandru
Eduard Alexandru - avatar