For example,
//Package1/File1.java
class A{
...
}
public class File1{
...
}
How can I use the class A in the different File2.java? And what's the package that A is belong to? Package1 or default? Thank you!
For example,
//Package1/File1.java
class A{
...
}
public class File1{
...
}
How can I use the class A in the different File2.java? And what's the package that A is belong to? Package1 or default? Thank you!
It's simple. Create an instance of the class File1
inside the main method of File2.java
and do all your work there.
//package1/File2.java
public class File2
{
...
}
public File2() //constructor
{
}
//Main method
public static void main(String[] args)
{
File1 f1 = new File1();
//do your rest of the work here
}
You can't use the class A in File2.java
because it's not public, and you can't have more than one public class in a .java file.
In order to access class A inside File2.java
, you have to create another java class named A in another java file named A.java
, and then make this A class public, and create instance of A inside File2.java
.
Inside A.java
:
//package1/A.java
public class A{
...
}
public A() //constructor
{
...
}
Now in File2.java
:
//package1/File2.java
public class File2()
{
...
}
public static void main(String[] args)
{
A objA = new A();
//do your rest of the work here
}
Go through the following link for a better understanding: Why can't two public classes be defined in one file in java?
Both the file belong to same package that package1/file1.java. See understand like this : A class like file1.java can have many sub classes as "class A" but the public class can only be that class which has same name as file (file1.java) class. I think I make some sense here.