0

I have an arrayList of type "customer" which im trying to add some objects if same type to. when i use the add() method I get an error and a red line under that command The code works fine other than that part.

public class Admin {
public static ArrayList<Customers> customers = new ArrayList<>();    
Customers owner = new Customers("admin", "admin", 0);
Customers c = new Customers("test","123",0);
customers.add(c); //error is here
customers.add(new Customers("test","123",0)); //tried this one too but it doesnt work either //it says illegal start of type and not package exists }

//normal constructor

public class Customers {
private String username;
public String password;
private int points;
private String Status;

public Customers(String username, String password, int points ) {
    this.username = username;
    this.password = password;
    this.points   = points;
}}
1
  • 2
    Your code is not inside of a method in Admin, it is in the class scope. The other code works because they are declaring variables which will be interpreted as class fields which would not give an error, but .add cannot be used outside of a method. Commented Mar 31, 2022 at 17:50

1 Answer 1

1

There are at least two points you have to be aware of:

  1. Most statements in Java cannot be written outside of methods or static blocks.
  2. You need an instance of a class to use non-static fields or methods.

Since c is not static, you can use it only in the constructor or a non-static method.

public class Admin {
    ...
    
    public Admin() {
        customers.add(c); // this works
        customers.add(new Customers("test","123",0)); // this works
    }

    public void someMethod() {
        customers.add(c); // this does also work
        customers.add(new Customers("test","123",0)); // this works
    }

    static {
        customers.add(c); // this does not work, because c is non-static
        customers.add(new Customers("test","123",0)); // this works
    }

    public static void someStaticMethod() {
        customers.add(c); // still doesn't work, because c is non-static
        customers.add(new Customers("test","123",0)); // this works
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.