Matty
Matty

Reputation: 35

why is it possible to create String.java?

Just trying to understand why I am able to create String.java file and it is compiled without any errors. As far as I know, the classloader chain will go to Bootstrap classloader and it has already loaded Sting.class. Could you pls help me in understanding?

Upvotes: 0

Views: 84

Answers (2)

overhead
overhead

Reputation: 11

As highlighted by Jesper, the uniqueness of a class is determined by its fully qualified name i.e., package..

Try importing both the String classes in another class, and you will observe the difference when you will try to use it.

import java.lang.String;
import com.myclass.String;

Now, for resolving the ambiguity, you need to refer a class by its fully qualified name.

Upvotes: 0

Jesper
Jesper

Reputation: 206956

A class is not identified by just its name, but by its fully-qualified name, which is the name of the package followed by the name of the class.

If you create your own String class in some package com.myapp, then its fully-qualified name will be com.myapp.String. It doesn't conflict with the standard String class, which has the fully-qualified name java.lang.String.

Of course, it's going to be very confusing when you do this, especially because classes in the package java.lang are imported by default. Therefore, in practice you should never write your own class String, or name any of your own classes the same as classes from the standard library (especially standard classes from the package java.lang).

Upvotes: 3

Related Questions