user2101454
user2101454

Reputation: 291

How do I call a public static void that is in a different class.

I have 2 classes, MainActivity and MainGame. If I have a public static void in MainActivity, and one in MainGame. How would I execute the one in MainGame from MainActivity?

For example, I have this:

Main Activity:

public static void 1()
{
2();
}

Main Game:

public static void 2()
{
//blah blah blah
}

Upvotes: 1

Views: 4617

Answers (2)

Govind Balaji
Govind Balaji

Reputation: 639

In Java All Names must start with a '_' or alphabet.

So, we can take the method names 1 as _1 and 2 as _2.

The syntax for calling static methods in other classes is ClassName.MethodName(arguments).
So, in this case you would change the code as follows:

class MainActivity{
public static void _1()
{
MainGame._2();
}
}
class MainGame{
public static void _2()
{
//blah blah blah
}
}

Upvotes: 1

rainkinz
rainkinz

Reputation: 10393

2 isn't a valid method name I think, but if it were you'd just do:

MainActivity.2();

but let's say it isn't and you called it two instead, then maybe you're looking for

public class MainGame {
    public static void one() {
        System.out.println("called one()");
    }
}

public class MainActivity {

    public static void two() {
        MainGame.one();
    }

}

Upvotes: 4

Related Questions