| Author |
Calling a Method from another Class
|
Bernard Shapiro
Greenhorn
Joined: Apr 07, 2003
Posts: 6
|
|
I have a Customer class and an App class. in the Customer class I have a setBalance() method which receives a double. I wish to send the double from within the App class. I have tried to do it like this: Customer.setBalance(bal); But I get this error: "App.java": Error #: 308 : non-static method setBalance(double) cannot be referenced from a static context at line 84, column 18 what is the correct way to use this method from within the App class?
|
 |
Bernard Shapiro
Greenhorn
Joined: Apr 07, 2003
Posts: 6
|
|
btw, both of these classes are in the same file App.java ----------------- In the App Class: switch (choice) { case ADD_CUSTOMER: { //Read in Blanace from user System.out.print ("Input Balance: "); double bal = (Keyboard.readDouble()); Customer.setBalance(bal); } ---------- In the customer class: //SET METHOD: stores balance public void setBalance(double newBalance) { balance = newBalance; }
|
 |
Francis Siu
Ranch Hand
Joined: Jan 04, 2003
Posts: 867
|
|
hi Bernard I think you call the setBalance() method in the main method or some static method,so that you need to add the static in the setBalance() method. In your code If it is not clear,please post again thanks
|
Francis Siu
SCJP, MCDBA
|
 |
Nick Delauney
Ranch Hand
Joined: Sep 28, 2002
Posts: 43
|
|
I think what you need to do is create a Customer object in your app class. Customer myCustomer = new Customer(); then you can perform the method on that instance. myCustomer.setBalance(bal); keep in mine a Customer should have a balance atribute, in the customer class you should have double bal; However the previous poster also is correct - but it all depends on how you want to implement your code. BTW: In English the error is saying you did not create and object yet you want to use a method, and the method has not been created yet because its not static. (Static meaning it is there in the class regardless of an instance of the class.) your error: App.java": Error #: 308 : non-static method setBalance(double) cannot be referenced from a static context at line 84, column 18
|
N.D:"Anything worth having, takes time to get"
|
 |
 |
|
|
subject: Calling a Method from another Class
|
|
|