2014-10-29 102 views
-1

我嘗試在使用NetBeans IDE的java中製作一個簡單的類。每當我嘗試執行它時,它都會給出這樣的警告:「從靜態上下文引用的非靜態變量」。任何人都可以告訴我爲什麼會發生,以及如何解決它。提前Thanx。從靜態上下文引用的非靜態變量

public class HW3Q4 { 
class Payment{ 
    private double amount_payment; 

    public void set_amount(double amount){ 
     amount_payment = amount; 
    } 

    public double get_amount(){ 
     return amount_payment; 
    } 
    public void paymentDetails(){ 
     System.out.println("The amount of the payment is: "+amount_payment); 
    } 
} 
public static void main(String[] args) { 
    // TODO code application logic here 

    Payment p1 = new Payment(); 
    p1.set_amount(34000.00); 
    p1.get_amount(); 
    p1.paymentDetails(); 
} 

} 
+2

'付款p1 =新HW3Q4()。新付款();'由於付款是內部類 – 2014-10-29 11:05:27

+1

或者,它看起來像你想'靜態類付款'。 – bcsb1001 2014-10-29 11:06:28

+1

'class Payment'應聲明爲'static'。 – 2014-10-29 11:07:04

回答

0

您的付款類是嘗試行爲類似於說你的類HW3Q4像私有String在MyString中的字符串場HW3Q4內。所以爲了避免錯誤使用:

HW3Q4 h = new HW3Q4(); 
Payment p1 = h.new Payment(); 
+1

使內部類「靜態」或使其成爲頂級類會更直接。這種Java語法是恕我直言,使語言「功能完整」,但不應該用於現實世界的代碼, – 2014-10-29 11:07:31

+0

同意但PO想知道爲什麼和如何克服。所以是的,這可能是其中一種可能性。 – SMA 2014-10-29 11:08:51

1

您在創建對象時出錯。因此,這會幫助你:

public class HW3Q4 { 


    class Payment{ 
     private double amount_payment; 

     public void set_amount(double amount){ 
      amount_payment = amount; 
     } 

     public double get_amount(){ 
      return amount_payment; 
     } 

     public void paymentDetails(){ 
       System.out.println("The amount of the payment is: "+amount_payment); 
     } 
    } 


    public static void main(String[] args) { 
    // TODO code application logic here 

     HW3Q4 newInstance = new HW3Q4(); 
     newInstance.init(); 
    } 


    public void init(){ 
     Payment p1 = new Payment(); 
     p1.set_amount(34000.00); 
     p1.get_amount(); 
     p1.paymentDetails(); 
    } 

} 
0

你宣佈獨立Payment類的HW3Q4每個實例。相反,我想你想在自己的文件(Payment.java)中聲明Payment,這將是首選,但我想你可以聲明它爲static內部類 - 只需將class Payment { /* ... */ }更改爲static class Payment { /* ... */ }即可。

相關問題