Say I've a code like:
import java.util.Date;
import my.own.Date;
class Test{
public static void main(String [] args){
// I want to choose my.own.Date here. How?
..
// I want to choose util.Date here. How ?
}
}
Should I be full qualified class names? Can I get rid of the import statements? Is such a scenario common in real world programming?
You can omit the import statements and refer to them using the entire path. Eg:
But I would say that using two classes with the same name and a similiar function is usually not the best idea unless you can make it really clear which is which.
When you call classes with the same names, you must explicitly specify the package from which the class is called.
You can to do like this:
Output:
If you really want or need to use the same class name from two different packages, you have two options:
1-pick one to use in the import and use the other's fully qualified class name:
2-always use the fully qualified class name:
You can import one of them using import. For all other similar class , you need to specify Fully qualified class names. Otherwise you will get compilation error.
Eg:
This scenario is not so common in real-world programming, but not so strange too. It happens sometimes that two classes in different packages have same name and we need both of them.
It is not mandatory that if two classes have same name, then both will contain same functionalities and we should pick only one of them.
If we need both, then there is no harm in using that. And it's not a bad programming idea too.
But we should use fully qualified names of the classes (that have same name) in order to make it clear which class we are referring too.
:)
I hit this issue when, for example, mapping one class to another (such as when switching to a new set of classes to represent person data). At that point, you need both classes because that is the whole point of the code--to map one to the other. And you can't rename the classes in either place (again, the job is to map, not to go change what someone else did).
Fully qualified is one way. It appears you can't actually include both import statements, because Java gets worried about which "Person" is meant, for example.