George Irimiciuc
George Irimiciuc

Reputation: 4633

How to see methods from other class

I got a class where I made multiple methods, but I want to put some of them in another class, since they do other things. How can I have my first class still use my methods?

Class A had 15 private static methods(they are static since they just return values and I don't need to define an object)

I created Class B in the same package and when moving 5 methods in it, the main function from A will not detect them when used.

Upvotes: 0

Views: 86

Answers (2)

m0skit0
m0skit0

Reputation: 25873

Your problem is the visibility. private means only the wrapping class can see these methods.

Set the visibility to default (if both classes are in the same package) or public if they're in different packages.

For example, classes A and B are in same package:

// A.java
public class A {
    static void oneMethod();
}

// B.java
public class B {
    private static void anotherMethod() {
        A.oneMethod();
    }
}

or in different packages:

// A.java
public class A {
    public static void oneMethod();
}

// B.java
public class B {
    private static void anotherMethod() {
        A.oneMethod();
    }
}

Upvotes: 2

Erik Pragt
Erik Pragt

Reputation: 14627

That's because you've defined the methods as private. You should define them as package protected (remove the 'private' part), or public (replace private with public).

Having said that: having a class with 15 private static methods is so uncommon that I'd add the label 'bad practice' to it. Can you share your code, so that it's more clear what these methods are doing? Unless you are creating a utility class, say StringUtils, I'm pretty sure there's a small chance you need any static methods at all.

Upvotes: 0

Related Questions