I get a compile error in MyTest.java. It doesn't recognize the method MyFunc which it calls. Here's what I have, Both MyTest.java and MyClas.java are in c:\java. After succesfully compiling MyClass.java, I copied MyClass.class to my c;\java\com\util directory, since MyTest.java imports it. I want to call the MyFunc function in MyClass.java from main in MyTest.java. Also, it it OK to have a .java class file (such as my MyClass.java) that does NOT have a function main in it? Here's my MyClass.java file: package com.util; public class MyClass { void MyFunc() { System.out.println("It printed in MyClass"); } }
Here's my MyTest.java file:
import com.util.*; public class MyTest { public static void main(String[] args) { MyTest obj = new MyTest(); obj.MyFunc(); } }
Bill Tripper
Greenhorn
Joined: May 30, 2001
Posts: 24
posted
0
You've specified class MyClass as belonging to package com.util. Class MyTest has no package specification. That is, these two classes are not in same package. Within class MyClass, you've defined method MyFunc() as "void MyFunc()". You're not specifying any access modifier, i.e, you're using the "default" modifier. This makes method MyFunc() accessable only within the same package. Since class MyClass is not in the same package as class MyTest, method MyFunc() is not accessable from within class MyTest. The solution is to define method MyFunc() as "public void MyFunc()". Also, typically method calls start with a lower case letter. That is, it's more normal to name your method "myFunc" or myMethod" instead of "MyFunc".
Fred Abbot
Ranch Hand
Joined: Jun 01, 2000
Posts: 300
posted
0
By importing files it does not neccaserly give you rights to the methods of other objects myTest does not have a method called myFunc()hencs the compiler error if you were to extend instead of importing it may help yes you can have java files without a main method
Notice obj is a new MyClass rather than a new MyTest. Also myFunc() is public. main() only has to be in the class that "kicks off" the application. I also had to replace the * in the import statement with the name of the class (MyClass) before it would compile. [This message has been edited by Marilyn deQueiroz (edited July 24, 2001).]
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt