Reputation: 1909
I am new to JAVA and am attempting to call a method from a class that prints out a message using the same method within another class. I am very new to java and really want to learn.
What I want to do is call the getAllCustomerInfo() method from the CustomerInfo{} class which is being called from the Customer class. When I try to run the code I get the error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static field c
If I make c static (static Customer c = new Customer();) and try to run my code it only prints the commas out from the getAllCustomerInfo() method and not the getName(), getAddress etc information.
Any ideas? Thank you.
CLASS 1:
public class Customer {
//Assume I have getters and setters and fields
//Method I want to use in another class
public String getAllCustomerInfo() {
String message =
getName() + "\n" +
getAddress() + "\n" +
getAge();
System.out.println(message);
return message;
}
} //END OF CUSTOMER CLASS
CLASS2:
//Class I am trying to call method from
public class CustomerInfo {
Customer c = new Customer();
public static void main(String args[]) {
//Code where I am trying to access the method from the Customer class
while (choice.equalsIgnoreCase("y")) {
System.out.print("Enter a customer number: ");
int customerNumber = sc.nextInt();
String customerInformation = sc.nextLine();
// get the Product object
Customer customer = CustomerDB.getCustomer(customerNumber);
//Check if customer exits in DB
if (customerNumber == 1) {
// display the output
System.out.println(c.getAllCustomerInfo());
} else {
System.out.println("There is no one like that in the DB.");
}
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
Upvotes: 0
Views: 488
Reputation: 2195
In the CustomerInfo
class, c
is a instance variable which will not exist without an object instance of CustomerInfo
class. Since you are referring it from static context you will get such error. You have to make c
variable static
or move it inside the main
method.
public class CustomerInfo{
static Customer c = new Customer();
public static void main(String args[]) {
// your implementation
}
}
OR
public class CustomerInfo{
public static void main(String args[]) {
Customer c = new Customer();
// your implementation
}
}
Upvotes: 1