Support Forums

Full Version: Making methods available within classes?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hi all,

I'm working on a little java program and I'm using classes. Though, I'd like to make some methods to be able to be used by any class in the package. Is this possible? And if so, can you provide an example on how to declare this?

Thanks,
Combus
Yes, of course it is possible, I do that

1- Create 2 classes
2- In the main class, create a main method, and in the main method, create an object of the second class
3- Use the object.method(parameters) to use the method of the other class

Example:

Code:
package primos;
public class Main {
    public static void main(String[] args) {
        abcdefg ole = new abcdefg();
        System.out.println(ole.asdf(1,2));
    }
}
class abcdefg {
    public static int asdf(int a, int b) { return a+b; }
}
I meant something like sharing methods between classes. Because I'm working with 2-3 classes, and there are some methods I use in every class, so I wanted to be able to use the same method in all classes w/o having to remake it in every class, but without using an extra class (because it would require to declare new objects, which are not required due the kind of methods I re-use, which are just simple voids). But I've confirmed that's not possible, just with use of extra classes. Thanks anyways Smile
Well, think about it. If you have many large methods that you want to re-use, then a class for them is definitely suitable.
If they're just a couple of small methods, it's not gonna hurt to redefine them all in their own classes. ;)
I do not know of a way of doing what you're trying to do, though.
well yea of course its possible
(10-08-2009, 05:28 PM)HuNt3R Wrote: [ -> ]well yea of course its possible

Please post real answers; the members who create threads want solutions to their problems, not answers that state "it's possible."
(10-08-2009, 06:18 PM)Psycho Wrote: [ -> ]Please post real answers; the members who create threads want solutions to their problems, not answers that state "it's possible."
Eustaquio has that covered
(10-08-2009, 07:06 PM)HuNt3R Wrote: [ -> ]Eustaquio has that covered
I don't know if you've read the OP's second post, but it indicated his question wasn't completely answered.
If you have no valuable input related to his question, it would be better unsaid. Even if you believe the question has been answered, it doesn't make it okay to throw a useless answer in.
couldn't you just create a void method in one of the classes. I mean, if you put a new method in one of your classes and create an instance of those classes in your other classes, you could just use them.

class 1:
method comes ehre

class 2:
instance of class 1 -> class1.method()
You could also just make the method static on some conditions.
Pages: 1 2