Java imports. Does it support import as aliasing? [duplicate] - java

In Python you can do a:
from a import b as c
How would you do this in Java, as I have two imports that are clashing.

There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;

As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional
use of fully qualified names is not an undue burden (unless the library
really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language
change.
So I guess we will not see this feature in Java anytime soon :-P

It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()

Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.

Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.
If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7

It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;

Unless there are problems with non-default constructors you can always do this (while we all wait for the Java language specification to catch up):
public class YaddaYadda
{
private static class ZU extends eu.zrbj.util.ZrbjUtil_3_0 { }
public void foo (String s)
{
if (ZU.isNullOrEmpty(s))
{
// ...
For project-wide use the 'import' class can go into a separate class file, giving a single point of definition for the import.
This is a lifesaver especially with regard to 'library' classes, meaning collections of static utility functions. For one thing it gives you the ability to version these beasts - as shown in the example - without major inconvenience for the user.

Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.

Related

how does java know which class do we mean [duplicate]

In Python you can do a:
from a import b as c
How would you do this in Java, as I have two imports that are clashing.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional
use of fully qualified names is not an undue burden (unless the library
really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language
change.
So I guess we will not see this feature in Java anytime soon :-P
It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.
If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Unless there are problems with non-default constructors you can always do this (while we all wait for the Java language specification to catch up):
public class YaddaYadda
{
private static class ZU extends eu.zrbj.util.ZrbjUtil_3_0 { }
public void foo (String s)
{
if (ZU.isNullOrEmpty(s))
{
// ...
For project-wide use the 'import' class can go into a separate class file, giving a single point of definition for the import.
This is a lifesaver especially with regard to 'library' classes, meaning collections of static utility functions. For one thing it gives you the ability to version these beasts - as shown in the example - without major inconvenience for the user.
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.

Understanding the difference between extending a class and importing a class [duplicate]

This question already has answers here:
What's the difference between importing and extending a class?
(10 answers)
Closed 7 years ago.
I have seen several threads that define extending a class as a way for a personalized class to inherit the methods of the class that it is extended to. When you import a class and create an instance of that class you have access to its methods, can someone please explain to me how extending a class to provide those methods to your own class is effectively different, in other words, the only difference I see is that when you import you create an instance of a standardized class, and when you extend you effectively turn your personalized class into the standardized class only with a different name. I am aware I am wrong, but the answers I have read have failed to help me fundamentally understand the difference.
Importing and extending are two very different things.
Importing
Classes are organized in packages, which provide a namespace facility that avoids name conflicts. Importing allows you to use the class in your code without the namespace information.
Importing is optional. You never have to import anything if you always use the fully qualified name of the class, but that makes your code hard to read.
If you want to make a list of Calendar objects, for example, you either import java.util.List, java.util.ArrayList and java.util.Calendar and use:
List<Calendar> array = new ArrayList<>();
Or import nothing and use:
java.util.List<java.util.Calendar> array = new java.util.ArrayList<>();
Sometimes you have two classes with the same name in different packages. In that case, if you use both of them in your code you can't import both. You will have to refer to one of them by their fully qualified name. For example:
List<java.awt.List> array; // you have to import java.util.List, but can't also import java.awt.List
Extending
When you extend in Java you are saying that the subclass is a type of the original class. That's the most important aspect you have to be aware of when using extends. Is you say Bus extends Vehicle you are saying that Bus is a Vehicle. You not only inherit all the non-private methods and fields of the superclass, but also can use the subclass anywhere you could legally use the superclass. For example, if you have this method:
public park(Vehicle v) {
v.drive();
v.turn(Direction.LEFT);
v.stop();
}
you could pass a Bus as an argument, because Bus is a Vehicle.
parkingLot.park(new Bus());
and the drive(), turn() and stop() methods will be called in the Bus. That is polymorphism.
Although you inherit methods, inheritance is not the best way to reuse code. Most of the time when you need to reuse code you can do it by using composition (making your class have a reference to another class, instead of being one). A Car shouldn't extend Motor because a car is not a motor, but it could have a motor and delegate a call to the motor's turnOn() method when the car's drive() method is called.
You can also have polymorphism without inheritance in Java using interfaces.
To make a simple example (but bad :/ ). Lets say you have a Person class.
public Person
{
int age;
string name;
}
Then you have different type of persons that inherit the Person class, eg.
public SoftwareDeveloper extends Person
{
string codingLanguage;
}
Now you can easily create a SoftwareDeveloper and use its attributes like this:
public static void main ()
{
SoftwareDeveloper developer = new SoftwareDeveloper();
System.print.out(developer.name);
}
If you would "import" instead, you would have to create an instance of Person in SoftwareDevelopers constructor and make it public. So your code would be to access the attribute:
public SoftwareDeveloper
{
public Person person;
string codingLanguage;
public SoftwareDeveloper(){
person = new Person();
}
}
public static void main ()
{
SoftwareDeveloper developer = new SoftwareDeveloper();
System.print.out(developer.person.name);
}
I think in small scale your reasoning works fine but the idea of extending is that your class inherits all the methods of the extended class.
But if you start with a simple idea or program and want to expand it massively the use of instantiating all the classes you need becomes much more consuming. On even a simple idea the increase in imports can explode.
Example:
Animal - warm blooded - biped - human
Animal - warm blooded - quadruped - feline - cougar - panther
Now you want to have your panther have all the methods of the 5 classes its built apoun.
So that 5 imports and objects you have to manipulate to get to all the methods you want to access. But if all these are extending each other you just have direct access to the methods. And this is a simple example now imagine a huge accounting program.
So point I trying to make....I think...Is that its much more prevalent and easier to understand the usefulness in extending classes when you look at it in the large scale.
Hope this helps or makes as much sense as it does to me.
Extending a class means that your class is "inheriting" the methods of the standard class; in other words, you are taking an existing class and building your class on top of it. That is how Java manages all objects (i.e. every class that you create actually extends the default Object class). When you import a class, on the other hand, you have access to all its functionality, but you cannot build on top of it as you could with inheritance.
Let's start with importing a class. You import a class in order to use it in another class, if that class is in another package. It's really just a shortcut that's saying when you see a class called X used, what I really mean if com.somepackage.X.
Extending is taking a class and using it as a base for a new class. There's alsorts of reasons to do this (well beyond the scope of an answer here) but the important thing is that you inherit the behaviour of the class you are extending and have the choice of whether or not to override that behaviour or add additional behaviour.
For good example of classes being extended, look at the Collection API in java.util where you can see java.util.AbstractList is extended to ultimately create two different types of list, each with different characteristics - java.util.ArrayList and java.util.LinkedList.
Lets look on an example.
We have class which provide an update function to database and containing a String variable.
public class DBupdate {
public String StrVar = "Hello";
...
public void doUpdate(String expression) {
try {
connect();
runExp(expression);
disconnect();
} catch ...
}
}
If you import it. You will do something like
log(new DBupdate.StrVar);
String myExp = "UPDATE ..."; // SQL
new DBupdate.doUpdate(myExp);
If you extend.
log(StrVar);
String myExp = "UPDATE ..."; // SQL
doUpdate(myExp);
doUpdate() function and StrVar became part of your new class. So all functions and variables (which are public or protected) are part of your new class (inherited).
Example for usefull import (and not extend/inherit) is log4j. It is doing work like writing to console and into a file. But you want just to use it "log" function and no speacial functions it is using for its work.
Example for usefull inherit is java.lang.Thread. If you class became a thread it can be treated as a Thread and will be splitted to run parallel, if you use java.lang.Thread function "start()". (Override run() method to do so some stuff...)
At the very simplest case it can be said that, Import Statement improves readability and reduces the length of the code.
In java we implement dynamic loading, language import statement no class file is loaded at the time of import statement, when ever we are suing a class, at the time of only the corresponding .calss file will be loaded.
Extends-
In Java, when we wish to extend the usefulness of a class, we can create a new class that inherits the attributes and methods of another. We don't need a copy of the original source code (as is the case with many other languages) to extend the usefulness of a library. We simply need a compiled '.class' file, from which we can create a new enhancement. I could not find a better way to explain so just refer this link..(source -http://www.javacoffeebreak.com/java104/java104.html)

Get Eclipse to prefer static imports of nested classes

Assume we have a class FooCollection which contains a somewhat long list of static nested classes*:
public class FooCollection {
public static class FooA implements Foo {
// ...
}
public static class FooB implements Foo {
// ...
}
// ...
}
Assume now we have another class using all of these classes. Currently, Eclipse will auto-format this to import each class separately if we reference the class itself
import com.me.FooCollection.FooA;
import com.me.FooCollection.FooB;
import com.me.FooCollection.FooC;
import com.me.FooCollection.FooD;
// and then later something like
callBaz( FooA.class );
What I would prefer to avoid bloating imports and constant commits changing imports due to colleagues using IntelliJ, is having it imported as
import static com.me.FooCollection.*;
However, I can't seem to find anything to get Eclipse to do this. Is there something I am missing or any way to get Eclipse to do it this way?
Edit: I actually just checked and even new FooA() will still cause the imports to switch back to this, despite setting the start imports threshold.
*) I realize that this is not exactly a good design, but it's a legacy application and for the sake of it let's assume that the code cannot be changed.
Dave Newton is referencing the setting under "Organize Imports" in Window -> Preferences. You can set the threshold for importing using a wildcard. Looks like the default is 99 classes before going to the wildcard. If you set it at 2, it looks like it would do what you needed!
Not sure, if there is a way to make it to work globally, but there is a short cut to deal with one member at a time.
If you select FooCollection.FooA and press Ctrl + Shift + M will add the static import and also will update all other references with in that file.
I use this mostly to import Enums and constants.

Non-class functions in Java

I'm mostly a c/C++/objective-C programmer, presently working in Java on an android application. My question is simple: I want a utility function, preferably not associated with any class that I can invoke from anywhere in my project (#include of some sort necessary?).
I know I can make a public static function of a class and invoke it as Class.someFunction();. I would like to just have someFunction(); I'm not sure if this is possible in java, or what the syntax for it is.
You can achieve the same "effect" by using a static import, by adding the following import in each file that you want to use it in:
import static x.y.Class.someFunction; // or x.y.Class.*;
...
// some code somewhere in the same file
someFunction();
However, all methods in Java must be part of a class. Static imports just let you pretend (briefly) otherwise.
P.S. This also works for static fields.
You could use a static import:
import static com.example.MyUtilityClass.*; // makes all class methods available
// or
import static com.example.MyUtilityClass.myMethod; // makes specified method available
You don't see this used very often because, if overused, it causes harder-to-debug code (see the last paragraph at the link above).
Here's a related question about when it's advisable to use this.
Also, following the programming best practices, You should define all such common, frequently used functionality in some utility class where you can define your functions or fields(probably constants- i.e. static and final attributes) that is going to be used/called at different places within the API.
Although, you still need to import the Utility class.
Else define such functionality in the top most parent class in your API hierarchy structure, that way you even don't have to import the class.
Hope this helps.
thanks....!!!
Yeap import static..
For instance:
import static java.lang.Math.max; // Allowing to use max method anywhere in the source
class SomeClass {
int m = max( 1, 2 );// m now is 2 due t Math.max( int, int )
}

Java: Use import or explicit package / class name?

I'm writing a very basic app, extending the Swing JFrame. What are the differences between making an explicit reference:
public class LineTest extends javax.swing.JFrame {
...
or importing the class beforehand:
import javax.swing.JFrame;
public class LineTest extends JFrame {
...
When (and why) would you use one technique over the other?
There is no real difference; the generated byte code will be exactly the same. An import statement is really just a way to tell the compiler "when I write JFrame, I actually mean javax.swing.JFrame".
You might want to use fully-qualified package names if you have for example two classes with the same name in different packages. One common example from the standard library are the classes java.util.Date and java.sql.Date.
The only difference is in the source code. Using the fully qualified name leads to less readable code, so everyone uses imports pretty much exclusively. The only place where I've ever seen the fully qualified names used consistently is in generated code.
The only reason to use the fully qualified name in regular code is when you have to use two classes with the same simple name (e.g. java.util.List and java.awt.List) - in that case there is no alternative.
For the compiler it doesn't make any difference. The disadvantage of using the full qualified name is that you would have to write it each time you are using the class. I only use the full qualified name if I have two classes with the same name in different packages. This way you can differ between those two classes

Categories