Hi everyone,

I'm currently trying to do a bit of java programming after not looking near it for almost a year. Most of what I've been doing has been C/C++, and I was just wondering -

in C++ you could have a header file with functions only in it, say "MyFunctions.h"

int functionA ()
{
    return 10;
}

string functionB ()
{
    return "hello";
}

double functionC ()
{
    return 5.5;
}

And include this file in another - so you could just call "double d = functionC ();", so i was wondering is there a way to do this in Java, or would I have to put all the functions within a class, create an instance of the class and call them that way? A bit of a stupid question I know but any help would be much appreciated :)

From the code above, do you mean a constant? You can create a static class where you can just call MyClass.functionc(). You do not need to create a new instance of the class. If that is what you are looking for.

In Java you do this by creating a utility class with all those functions defined as static (so they don't need an instance to be created). A good example is the Math class in the standard Java API
http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html
you can simply import this class at the start of your program, then call the methods like Math.cos(x) or whatever.

ps
If you import static the class then you can use its static methods without prefixing the class name
ie

import static java.lang.Math.*;
...
x = cos(y);  // static method cos is resolved via the import static for Math

Ah right, forgot about static methods in java... it really has been a while :) thanks again!!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.