2015-04-29 16 views
0

在編寫獨立的Java應用程序時,我在靜態上下文中看到很多初學者代碼。 我曾經通過在main中創建一個類的實例並使用構造函數來解決此問題。有關靜態上下文的最佳實踐

我已經添加了一個非常簡單的獨立程序的例子,並想知道是否有「離開」靜態上下文的最佳實踐。

我也想知道是否有一些獨立的java程序應該在靜態上下文中或者在主要方法中做什麼,它的功能除了作爲每個獨立java程序的入口之外。

任何閱讀材料也歡迎!

import javax.swing.JFrame; 
import javax.swing.JLabel; 

public class ExampleStatic 
{ 
    JLabel label; 

    public static void main(String[] args) 
    { 
     //Option 1 - Work from static context: 
     JFrame frame = new JFrame(); 
     frame.setBounds(10,10,100,100); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JLabel staticlabel = new JLabel("static"); 
     frame.add(staticlabel); 

     frame.setVisible(true); 

     //Option 2 - Create instance, call initialisation function 
     ExampleStatic e = new ExampleStatic(); 
     e.initialise(); 

     //Option 3 - Create instance, handle initialisation in constructor 
     new ExampleStatic(true); 
    } 

    public ExampleStatic(){} 

    public ExampleStatic(boolean init) 
    { 
     JFrame frame = new JFrame(); 
     frame.setBounds(10,10,100,100); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     label = new JLabel("constructor"); 
     frame.add(label); 

     frame.setVisible(true); 
    } 

    public void initialise() 
    { 
     JFrame frame = new JFrame(); 
     frame.setBounds(10,10,100,100); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     label = new JLabel("init function"); 
     frame.add(label); 

     frame.setVisible(true); 
    } 
} 
+0

選項2和選項3都很好。 –

回答

0

選項2和選項3無一不是精品,既提供鬆耦合,以及如果你想使用您的實例在其他地方其他類中,你可以輕鬆地使用它。但是,如果您將使用Main方法編寫所有內容,您將放棄範圍和可重用性。

+0

我知道這一點,但我想知道是否還有在靜態上下文中應該做的事情,而不是在構造函數或實例對象函數中。 – JohannisK

0

JVM需要main是靜態的,之後你可以自由地做你想做的事情。我會調用一個非靜態的「第二主」來處理初始化,然後用不同的方法(或類)進一步處理。

我會避免把東西放在構造函數中,除非你真的覺得它是適合它們的地方。

+0

你的意思是靜態主體除了作爲切入點之外沒有其他功能,最佳實踐是儘快離開它? – JohannisK

+0

如果你不想離開,你不必離開它。它是靜態的,因爲JVM,而不是程序員。 – Kayaman