public class MainTest { PracticeWork1 grades; MainTest() { grades = new PracticeWork1(); init(); } public static void main(String[] args) { new MainTest(); } public void init() { testOut(); grades.adder(); testOut(); grades.adder(98); testOut(); } } 

example 2

 public class MyWin extends JFrame { private static final long serialVersionUID = 1L; public MyWin() { Container c = getContentPane(); c.setLayout(new BorderLayout()); Panel child= new Panel(); c.add(child); setTitle("Example window"); setPreferredSize(new Dimension(640, 480)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); // отображаем окно } public static void main(String args[]) { new MyWin(); } } 

Is it correct to create in the main method the object of the class in which this main is located, and not to prescribe most of the logic in it?

  • one
    what exactly confuses you? - etki
  • Is it normal to write such code? because the Designer essentially changes its meaning. - Kraken

2 answers 2

If I understand your question correctly, it’s about whether you can put class logic in the constructor.

Technically, this is possible and will work, but in terms of the meaning of the code, this is not very good. The constructor must construct the class, and the action must be run by some method .

If your project is small, you can break this rule (like many others), but for a more or less serious project, I would advise you to leave only initialization in the constructor.

  • Will it be considered correct if you place in the constructor, for example, the method to which the program logic is concentrated. If not, how will they write such programs correctly? - Kraken
  • @DmitryZherebko: In my opinion - wrong. In the constructor initialization, the logic in the methods. - VladD
  • @DmitryZherebko: To make the calling code look something like this: Worker w = new Worker(); w.work(); Worker w = new Worker(); w.work(); . - VladD

Logic in the constructor is not a good idea. This code is hard to test. Also in case of an exception in the constructor there may be problems. I would recommend initialization not in the constructor:

 public class MainTest { PracticeWork1 grades; MainTest() { } public static void main(String[] args) { MainTest test = new MainTest(); test.init(); } public void init() { grades = new PracticeWork1(); testOut(); grades.adder(); testOut(); grades.adder(98); testOut(); } } 

For this, a Builder template would work well.