Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am completely new to Java and came across a question that how java compiler creates object of one class in another class. For example :

I have class A as below :
Java
class A{}

//I have class B with main method :

    class B{

        public static void main(String[] args){

        A a = new A();
        
        System.out.println(a);
        
    }
}

Here is the question: I wrote class A in one separate txt file and class B in another txt file. When I compile Class B How compiler knows that class A exists since there is no trace of class A in class B. We are not giving path of Class A and we are not not giving any clue that class A exists. But how java compiler knows and create object for Class A in class B. This might be a silly question but it is not letting me to proceed further without an answer. Thanks in advance.

What I have tried:

I have class A as below :
Java
class A{}


I have class B with main method :
Java


class B{

public static void main(String[] args){

A a = new A();

System.out.println(a);

}
}
Posted
Updated 21-Aug-16 2:26am
v2
Comments
Mohibur Rashid 20-Aug-16 23:16pm    
in this case I am guessing your class a is in the same directory as b. That is when javac is getting this unknown class and not seeing any using related statement, it will look for a.java in the current directory.

1 solution

When you compile B then the Java compiler tries to find all associated classes in order to create a runnable program. If it cannot find the A.class file, but it can find the A.java file then it will build the class automatically. Try running the command
java -verbose B.java

and you will see it in action.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900