V
V
Vladimir2018-03-21 23:23:01
Java
Vladimir, 2018-03-21 23:23:01

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

3 answer(s)
A
Andrey, 2018-03-22
@poslannikD

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.
As an advertisement:
Open a new world, read about singelton and other patterns!!!!!!
Develop in it, master c or c++ + asm, some of the stupid questions will disappear by themselves!!!!

M
MaxLich, 2018-03-22
@MaxLich

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.

M
Maxim Fedorov, 2018-03-22
@qonand

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 question

Ask a Question

731 491 924 answers to any question