How does creating a instance of class inside of the class itself works?

前端 未结 5 660

What makes it possible to create a instance of class inside of the class itself?

public class My_Class
 {

      My_Class new_class= new My_Class();
 }
         


        
5条回答
  •  失恋的感觉
    2020-11-30 01:57

    The main thing I always see myself creating an instance from within the class, is when I am trying to reference a non-static item in a static context, such as when I am making a frame for a game or whatever, I use the main method to actually set up the frame. You can also use it for when there is something in a constructor that you want to set (like in the following, I make my JFrame not equal to null):

    public class Main {
        private JFrame frame;
    
        public Main() {
            frame = new JFrame("Test");
        }
    
        public static void main(String[] args) {
            Main m = new Main();
    
            m.frame.setResizable(false);
            m.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            m.frame.setLocationRelativeTo(null);
            m.frame.setVisible(true);
        }
    }
    

提交回复
热议问题