-1

I tried making a simple class in java using netbeans IDE. Whenever I try to do execute this it gives such warning."non static variable referenced from static context".Can anyone tell me why it happens and how to solve it. Thanx in advance.

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 Answers3

1

You make a mistake in creating the object. So this would help you:

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

}
Lukas Hieronimus Adler
  • 1,063
  • 1
  • 17
  • 44
0

Your payment class is within the HW3Q4 which try to act similar to say a string field within your class HW3Q4 like private String myString. So in order to avoid the error use:

HW3Q4 h = new HW3Q4 ();
Payment p1 = h.new Payment();
SMA
  • 36,381
  • 8
  • 49
  • 73
  • 1
    It would be much more straight forward to make the inner class `static` or make it an top level class. This java syntax is IMHO to make the language "feature complete", but should never be used in real world code, – Gyro Gearless Oct 29 '14 at 11:07
  • Agreed but PO wanted to know why and how to overcome. So yes that could be one of the possibility. – SMA Oct 29 '14 at 11:08
0

You are declaring a separate Payment class for each instance of HW3Q4. Instead, I think you want to declare Payment in its own file (Payment.java), which would be preferred, but I guess you could declare it as a static inner class - just change class Payment { /* ... */ } to static class Payment { /* ... */ }.

bcsb1001
  • 2,834
  • 3
  • 24
  • 35