How does a java class access another java class?

This is a very interesting topic to talk about.

You have two classes in same folder as well the same class is using the classes from the library.

How is that happening?

Let say we have a folder by name class access and it have the described classes

Folder Structure.


class Radio 
System.out.println("I am a Radio");


class Car 
Radio r;
int tyres=4;

System.out.println("I am a  Car:");
System.out.println("I have "+tyres+" tyres");
new Radio();

public static void main(String[] args)
new Car();

If observed properly, class Car is using the class Radio which is in the same folder  as well as class System which is Java library.

Example of a class accessing another class.

How does a compiler discovers the class in folders as well as class in library?

Rule is very simple, whenever a compiler encounters 
Way in which compiler finds the class.
- So whenever a class is accessed in some other file, the discussed rules are followed.

So if the class is in the same folder it is found first, if not found it tries to search it in java.lang package, if not found in java.lang it tries to find some import statements and and try to search in the imported package.

Never give your class a name similar to those of the class in Java library. 

Imagine you write a class and name it as String. 
Later you write another class which is trying to access class String of java.lang package, 

What will happen? 

The other class wont be able to access java.lang.String as whenever compiler is trying to access String , it finds it in the same folder hence, it never goes to the second option of finding it in java.lang.

Is there any way out?

- Yes, when the class String is supposed to be accessed in another class it should be used with qualified import, i.e.
java.lang.String s="Tom";

If done by this way, compiler never goes through the rule, it searches it directly in the package specified.


Post a Comment