静态上下文引用的非静态变量

时间:2014-10-29 11:02:18

标签: java class oop object static

我尝试使用netbeans IDE在java中创建一个简单的类。每当我尝试执行此操作时,它都会发出警告。"非静态变量引用静态上下文"。任何人都可以告诉我它为什么会发生以及如何解决它。提前完成。

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();
}

}

3 个答案:

答案 0 :(得分: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();
    }

}

答案 1 :(得分:0)

您的付款类位于HW3Q4内,其尝试类似于类HW3Q4中的字符串字段,如私有字符串myString。所以为了避免错误使用:

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

答案 2 :(得分:0)

您为Payment的每个实例声明了一个单独的HW3Q4类。相反,我认为你想在自己的文件(Payment)中声明Payment.java,这是首选,但我想你可以将它声明为static内部类 - 只需更改{ {1}}至class Payment { /* ... */ }