Answer the question
In order to leave comments, you need to log in
Easy question on OOP theory. Creating an instance of a class in the same class?
Hello! Such a controversial question, I did not google a sane answer.
Let's create the Animal class. Is it possible to create objects of the Animal class directly in the same class and work with these objects in other classes? Or is it correct to create objects of the Animal class, say, for example, in main ()?
public class Animal {
Animal cat = new Animal ();
}
Answer the question
In order to leave comments, you need to log in
Is it possible to create objects of the Animal class directly in the same class and work with these objects in other classes?-can. To expand consciousness, you can look at anonymous and nested classes, it will show what else is possible))))
Or is it correct to create objects of the Animal class, say, for example, in main ()- the correctness depends on the scope of the program and architecture. Mine is the entry point to the application. But to create at once and everything in it is pure madness, even for scripts.
This is used in some patterns (singleton, factory, etc.), also for testing a class, you can declare the main () method in it and create an instance of this class in the body of this method and work with it. But this is more suitable for small testing (one-time) and for small training programs, in serious production projects this is not necessary.
You can create something, how much it is right - it depends entirely on the specific tasks. If you want a more detailed answer - describe the problem in more detail
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question