Using variables from my custom class file in my main class file
Hi everyone,
I am currently learning about creating my own class files. I was wondering if there is a way to create a variable in one class file, and use that variable in my main class file without having to declare that variable in my main class first.
For example
public class CustomClass
{
public int someNumer = 0;
public void createNumber()
{
someNumber = 75;
}
}
public class mainClass
{
public static void main(String[]args)
{
CustomClass c = new CustomClass();
c.createNumber();
System.out.prinln("The number "+someNumber+"has been passed from the cutom class to the main class");
}
}
Obviously this is not what im going to use this for, but it gets the general idea across. If this is possible, it would be alot more convenient for what I want to do.
Thanks in advance
[928 byte] By [
Pheonixa] at [2007-11-27 3:45:28]

You can do this:
System.out.prinln("The number "+c.someNumber+"has been passed from the cutom class to the main class");
But that kind of sucks, because it's bad when one class directly refers to the internals (and fields are parts of the internals) of another class. You should declare someNumber in CustomClass as private. You should almost always declare fields private.
Marginally better, you could define an accessor in CustomClass:
private int someNumber;
public int getNumber() {
return someNumber;
}
and then use that in mainClass:
System.out.prinln("The number "+c.getNumber()+"has been passed from the cutom class to the main class");
That's better because the details of someNumber are hidden, but it's not great because (1) it at least suggests an implementation detail of CustomClass, and (2) it's now part of CustomClass's API, which means that you have to maintain it forever, even if you change CustomClass's implementation such that someNumber no longer exists.
The best thing to do is to move all functionality that uses someNumber into CustomClass itself. That's how you achieve encapsulation, which is the goal and design principle of object-oriented programming. With encapsulation, code becomes much easier to maintain.
By the way, when you post code on these forums, please wrap it in [code][/code] tags.
Also, following Java naming conventions. Class names start with an upper-case letter.