Gerard Maynes
Gerard Maynes

Reputation: 1

How can I call a method from one class to another?

So, I'm working in this class

Public class Java2MySql {
    public static void main(String[] args) {
        Java2MySql j = new Java2MySql();
        ...
    }
    public static String selectValue() {
        BlackBox blackBox = new BlackBox();
        ...
        switch(case) {
            case "C00":
                caixaNegre.waste();
                break;
        }
    }

And this other class

public class CaixaNegre{
    public static String waste(){
    ...
    }
}

The thing is I think it's correct, NetBeans does not show an error, but once I try to run it in the terminal to test it with my database, it shows the following message:

Java2MySql.java:50: error: cannot find symbol
    CaixaNegre caixaNegre = new CaixaNegre();
    ^
symbol:   class CaixaNegre
location: class Java2MySql

Why?

Upvotes: 0

Views: 41

Answers (1)

Rens Groenveld
Rens Groenveld

Reputation: 982

There is a difference between class methods and object methods. An object is an instance of a class. So to be able to call object methods, you first need an instance of that class (an object).

Your waste() method is a static method, meaning it becomes a class method. In order to call a class method, you use the full name of the class (Case sensitive) + the method name.

In you case, you should use:

CaixaNegre.waste();

instead of

caixaNegre.waste();

Remember: Everything that is static, belongs to the class. Everything that's not, belongs to an instance of the class.

It is good practice though, to make object instances of classes, rather than let everything be static. This way you are programming in an object-oriented way.

I'm not sure what you are doing, as in your error, it states that you are trying to make an instance of class CaixaNegre. In that case you have to remove the static keyword in your method waste.

As for your error: Is the CaixaNegre class in a different package perhaps? If so, did you import it?

Upvotes: 1

Related Questions