Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Basic class and object sharing question

Status
Not open for further replies.

leegold2

Technical User
Oct 10, 2004
116
0
0
Hi,

This is a basic question. I'm learning Java on XP. I'm noticing the way Java behaves that raises a question. Let's say I have folder with Test1.class it's got a printNames method that prints out an array. Now in same folder I write and compile Test2.java - it compiles with no errors. Test2 code might be this:

class Test2 {
public static void main (String arguments[]){
Test1 a = new Test1();
a.printNames();
}
}

And an array defined in test1 is outputted. Why does this happen? I do not explictly import test1 into the test2 class. What cache or default mechanism allows one class to see and use another class to make an object? Is there a way to prevent this, so that it will only happen if I explictly allow it in the code? Csn't this default capability cause trouble?

I also tried to clear all caches and temp files and removed the test1 class to the recycle bin. Test1 still worked in test2.

Help to understand appreciated.

Lee G.
 
You need to study more in basic knowledge in Java.
Code:
class Test2 {
  public static void main (String arguments[]){
      Test1 a = new Test1();
      a.printNames();
  }
}
As you have not used an access modifier in the first line of your code
class Test2 {
,your Test2 class can be accessed by the class in the same package.

Although you have not defined package, you have stored Test1 and Test2 in the same directory and they will belong to the same package.
It will be better if you post the code in Test1 class.
 
You can put access modifier on printNames method too
 
Thank you. I see that packages are considered directories now. I'm reading up on this, thanks....
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top