2013-02-26 26 views
1

我想編寫一個不接受參數的構造函數,所以如果我沒有實例變量,我用來創建一個構造函數,我有實例變量,我知道java創建一個默認的構造函數,如果我不有一個,但我被告知這是一個不好的編程習慣???(新課程)如果沒有任何實例變量,我將如何爲我的類編寫構造函數?

public class Validator { 
    public Validator() { 
    } 

    public String getString(Scanner sc, String prompt) { 
     System.out.print(prompt); 
     String s = sc.next(); // read user entry 
     sc.nextLine(); // discard any other data entered on the line 
     return s; 
    } 

    public int getInt(Scanner sc, String prompt) { 
     int i = 0; 
     boolean isValid = false; 
     while (isValid == false) { 
      System.out.print(prompt); 
      if (sc.hasNextInt()) { 
       i = sc.nextInt(); 
       isValid = true; 
      } else { 
       System.out.println("Error! Invalid integer value. Try again."); 
      } 
      sc.nextLine(); // discard any other data entered on the line 
     } 
     return i; 
    } 

    public int getInt(Scanner sc, String prompt, int min, int max) { 
     int i = 0; 
     boolean isValid = false; 
     while (isValid == false) { 
      i = getInt(sc, prompt); 
      if (i <= min) 
       System.out.println("Error! Number must be greater than " + min 
         + "."); 
      else if (i >= max) 
       System.out.println("Error! Number must be less than " + max 
         + "."); 
      else 
       isValid = true; 
     } 
     return i; 
    } 

    public double getDouble(Scanner sc, String prompt) { 
     double d = 0; 
     boolean isValid = false; 
     while (isValid == false) { 
      System.out.print(prompt); 
      if (sc.hasNextDouble()) { 
       d = sc.nextDouble(); 
       isValid = true; 
      } else { 
       System.out.println("Error! Invalid decimal value. Try again."); 
      } 
      sc.nextLine(); // discard any other data entered on the line 
     } 
     return d; 
    } 

    public double getDouble(Scanner sc, String prompt, double min, double max) { 
     double d = 0; 
     boolean isValid = false; 
     while (isValid == false) { 
      d = getDouble(sc, prompt); 
      if (d <= min) 
       System.out.println("Error! Number must be greater than " + min 
         + "."); 
      else if (d >= max) 
       System.out.println("Error! Number must be less than " + max 
         + "."); 
      else 
       isValid = true; 
     } 
     return d; 
    } 
} 
+2

構造函數之後的所有代碼如何與您的問題相關? – Dan 2013-02-26 00:25:45

+0

如果在構造函數中沒有任何要做的事,那麼你不需要聲明它。 – 2013-02-26 00:26:27

+0

我認識的人最近也在學習編程。他的教材中說:「總是創造吸氣和安裝者」,但他從未停下來問他爲什麼需要他們。現在他暴露私人變數並隱藏公衆。當你設計對象時,應該比「對象導向哲學」更符合特定部分的一般規則。這隻狗是否需要知道貓發出的聲音?也許是這樣,但它是否需要知道貓的飢餓的內部狀態呢?可能不會。構造函數會遵循類似的要點 – 2013-02-26 01:01:43

回答

7

構造函數用於「構建」一個對象。如果您沒有需要設置的值,則不需要構造函數。你可能也想考慮讓你的班級static。靜態意味着你不需要創建它的一個實例來訪問它的方法。當類的實例不包含特定的值時,這很有用,與您的非常相似!

+0

對於我的代碼,java默認構造函數的外觀如何? – babaysteps 2013-02-26 01:38:40

+0

默認的Java構造函數是由JVM爲您生成的。你不需要寫任何東西:) – christopher 2013-02-26 07:37:48

3

如果沒有實例變量,並沒有其它必需的任務來初始化類的一個對象,你可以離開了構造函數。 Java編譯器將爲您提供一個默認的編譯器。通常我只包含一個顯式的構造函數,當我確切地知道我需要它做什麼。

2

您不必顯式定義構造函數。已經有一個默認的構造函數。使用該構造函數並不是一個糟糕的編程習慣。

相關問題