ok, so i have created my own object in java. i have 5 different classes. 1 class is an abstract class, and it also has the main method in it. i created the objects in a different class. how can i access those objects from the main method?
New them up!
ok, so i have created my own object in java. i have 5 different classes. 1 class is an abstract class, and it also has the main method in it. i created the objects in a different class. how can i access those objects from the main method?
Figuring out how Java classes get references to each other is frequently a tough issue to grapple with.
One possibility, as another poster indicated, is to create them within your main method (via new) so that you'll have the references to them. Other possibilities are to have methods on those other classes which return references (factory methods) or to use some sort of 'locator' class which knows how to find all the various classes (and thus objects would need to register themselves when created).
Not sure about having the main method in an abstract class -- there might be a valid reason to do that, but offhand it seems an odd design.
Why are you putting main in the (abstract) base class? Even though I come from C/C++, from what I know of Java that sounds like a contorted, if not unworkable, design (someone correct me if I'm wrong).
Shouldn't main() be in it's own class that imports the declarations (or whatever you call them in Java) of your class heirarchy? A main class or a "driver class" or something?
ClassName instanceName = new ClassName();
instanceName.method();
you should just be able to use new like someone had suggested, the syntax isIt should work if the class file is in the same folder as the java file that you are writing.Code:ClassName instanceName = new ClassName(); instanceName.method();
Don't know how much easier this is than you way, but with this you don't have to type in the path each time.
P.S. This way also allows non-static methods
thanks for the reply.
see, i already did this in the other class file:
ClassName instanceName = new ClassName();
the problem was calling it. i could call it if i made the object static, and put the classname in front of the instanceName
Probably best if you posted full source code for us to take a looky. Keep in mind you can call methods of another class if its
a) declared as public
b) declared as protected, and the calling class is a subclass or in the same package
c) default (aka package private) - belongs to the same package.
I don't know that you have covered these yet in your class, but read all about access modifiers at http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html