Java import statements - java

I was reading about predefined methods and was learning about import statements. I have seen and often times used these to use certain predefined methods, but I've always seen them placed at the very beginning of a program. My question is, can these be placed inside a certain block of code so that it is only seen in that block? I'm not sure that there would ever actually be a reason for this, mostly just curious.

java files contains three parts:
package definition
imports definitions (optional)
the class (or interface/enum) definition.
and it also has to be in this order, you'll get compilation error if it's not in this order

No, you need to define it before of the class/interface, after the package statement.
So an import is always visible to the entire .class-file.
import lets you use members of other packages than your local package, without specifying the full name of a class (e.g. either you need to import java.util.List, or you need to use it's full name everywhere).
There is a tutorial on using package members by Oracle.
The order in a .class-file is defined as:
package specification (optional)
import statements
class / interface / enum definition

My guess is that will give you a compiler error. BUT you can effectively acheive the same thing if you specify the full package name of a class when you instantiate it.
E.g:
public String getString() {
return new com.package.some.Class("hello world").toString();
}
In this case you don't need to have an 'import' directive at the top of the class because you are telling the compiler inside the method that the class you want is located in the com.package.some package and the class is called Class.
This actually happens in the wild when for example you have to classes in different packages that have the same name. You can only import one of them, the other one you will have to inline the package definition inside the code.
import com.package.some.Class;
public class Yolo {
private Class classA;
private com.package.other.Class classB;
public Yolo(Class classA, com.package.other.Class classB) {
this.classA = classA;
this.classB = classB;
}
}
you can't just import both 'Class' objects and refer to them as Class because the compiler won't know which one. So, this is a valid situation where you will see this kind of thing happen for real.

From Oracle Docs :
Importing a Package Member
To import a specific member into the current file, put an import
statement at the beginning of the file before any type definitions but
after the package statement, if there is one. Here's how you would
import the Rectangle class from the graphics package created in the
previous section.

Related

Can import statements be used anywhere besides the beginning of a Java file?

In python, the import statement can be placed everywhere in the file, even inside a class, or an if.
Is there a way to accomplish the same thing in Java? I understand that it could be a bad practice not to put all the imports at the top of the file, I'm just wondering if it is possible in some way or not.
The very first statement in a Java file must be (if there is one) the package statement, followed by the import statements. They can not be placed in another location.
However, it is possible to skip the import altogether by using fully qualified class names (which I personally don't recommend). You need to use them everywhere you would have used the short, unqualified name.
import my.package.MyClass;
public class Test{
private MyClass instance = new MyClass();
}
can be rewritten as:
public class Test{
private my.package.MyClass instance = new my.package.MyClass();
}
According to the documentation here:
To import a specific member into the current file, put an import statement at the beginning of the file before any type definitions but after the package statement, if there is one.
So it seems that it is not possible.
Short answer : No it's impossible !
The import statement must be in the top of the file after the package statement (if exist).
You must know : You can use your imported class/interface or static method in all classes/interfaces in the same file including inner/nested classes.
There isn't a way, except maybe messing with bytecode if you count that. I suppose the best equivalent would be writing the fully qualified name of what you're looking to use.
Not sure why you would want to though.
No. They need to be at the top, after the package declaration.
An ordinary compilation unit consists of three parts, each of which is
optional:
A package declaration (§7.4), giving the fully qualified name (§6.7) of the package to which the compilation unit belongs.A compilation unit that has no package declaration is part of an
unnamed package (§7.4.2).
import declarations (§7.5) that allow classes and interface from other packages, and static members of classes and interfaces, to be
referred to using their simple names.
Top level declarations of classes and interfaces (§7.6).
This doesn't do a great job at conveying that the ordering of each part is strictly enforced, but the formal grammar does make this clear:
OrdinaryCompilationUnit:
[PackageDeclaration] {ImportDeclaration} {TopLevelClassOrInterfaceDeclaration}

Why did my import fail in Java?

I hava a StdDraw.java under the same folder of my working file, and picture() is a method within StdDraw.java.
However, I failed adding this line to import the method, suggesting by
package StdDraw does not exist
import StdDraw.picture
How could I possibly do that? Using package? Setting path? Or any modifications? I came from python and find it a little bit weird.
You can't import non-static methods (only classes and static members), and you don't have to!
If both your classes live in the default package then you should be able to do the following without any import statements :
myStdDrawObject.picture(); // if picture is non-static
or
StdDraw.picture(); // if picture is static
Note also, that you can't use static imports on classes that live in the default package.
If you are importing into the class which is there in same package then we no need to use any import.
if you want import mthods into the class use like below. You no need to put method name at the time of the import.
import packagename.StdDraw;
After importing your class, all non static methods of the class are available into the imported class.
when should you use static import? Only use it when you'd otherwise be
tempted to declare local copies of constants, or to abuse inheritance
(the Constant Interface Antipattern). In other words, use it when you
require frequent access to static members from one or two classes. If
you overuse the static import feature, it can make your program
unreadable and unmaintainable, polluting its namespace with all the
static members you import. Readers of your code (including you, a few
months after you wrote it) will not know which class a static member
comes from. Importing all of the static members from a class can be
particularly harmful to readability; if you need only one or two
members, import them individually. Used appropriately, static import
can make your program more readable, by removing the boilerplate of
repetition of class
names.
Read more about static import:
https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
When importing the package you do not need to import non static methods. You can read on Java - Packages here. It is easily explained and I found it useful when learning the same concept.
Even if you do not include import for the class which is present in the same folder, then also you can create object and call method of that class and also static methods.
You can create object and call the non-static methods.
StdDraw drawObj = new StdDraw();
drawObj.picture(); // if picture is non-static method
For static method, you can call it using class name only.
StdDraw.picture(); // if picture is static method.
What I recommend is to read up on packages and how code is organized in java. It is in someway similar to python, where a directory structure is used, but more to it in java. Maybe this will help
Java Tutorial- Packages

Is it possible to have a java program with just import statement

I saw one of the link Can we write a program without a class in core Java?
So going through this , it looks like we cant have a java program without atleast one single class.
But we have some requirement like,
I have a test Java program like::
package dashboardName;
import org.testng.Assert;
import org.testng.annotations.Test;
import pojoclass.MpsPojo;
import mpsLogicPack.MpsLogic;
public class TestLogic {
MpsPojo mpspojon = new MpsPojo();
MpsLogic mpslogicn = new MpsLogic();
#Test
public void firstTest() {
mpspojon.setMfr("m1");
mpspojon.setProd("p1");
mpspojon.setSchema("sch1");
mpslogicn.calculateAssert(mpspojon);
System.out.println("Printing from Final class");
}
}
The name of this package is dashboardName.
So if I will write a java program which has just the import statement of dashboardName. like:
FinalTest.java
import dashboardName.TestLogic;
So if I will execute this, what should be the result. Currently this is showing no error but showing No test run.
This may be a silly question because I belong to Perl backround and switching to Java. So pls excuse me.
Thanks
import statements only exist at compile time; they tell the compiler how to expand unqualified classnames. So, for example, import dashboardName.TestLogic; just means that all occurrences of the classname TestLogic should be expanded to dashboardName.TestLogic. But if you don't have any occurrences of the classname TestLogic, then this has no effect.
Assuming I understood your question correctly, then no. imports are basically just a list of lookups for which exact classes matches (or more formally, which Fully Qualified Names you are using) to the short name you're using in your actual application code.
On the other side, working without imports is entirely possible if you place all your classes in the same directory and only use system classes from java.lang and java.util.
You cannot run without a class. In order to execute a java program, you should either have a main() method, for which you need a class. Or you could use static initialization blocks of a class, for which, naturally, you need a class again.

How do I avoid unnecessary class references in Java?

I have two java classes (.java files). I want to be able to create new instances of an object in one class that were defined in the other class, without referencing the class name each time. In C# there are #using and includes, but I am only able to use import <pre-compiled code> in java. Is there a way to do this:
import TestClass;
and then simply call a function inside it without using
TestClass.TestFunction()
every time? I simply need to have all of my functions and objects to be separate from my Main class.
Assuming TestFunction is a static method in TestClass, you can use a static import:
import static TestClass.TestFunction;
// or
import static TestClass.*;
and then call it without using the class qualifier:
TestFunction(...);
Note this can lead to confusing/hard-to-read code – use static imports sparingly.
If you're using netbeans then you won't be finding any issue during the import of any java classes. And yeah that's true you can have only "pre-compiled classes" as import statement. If you are running on notepad then you need to compile your independent classes first and then your dependent classes. And if you use Netbeans or Eclipse or any other IDE then you do not have to worry they will manage by themselves, you just have to use proper package and class names
You can have two types of imports
import package1.Class1;
import static package1.Class2;
With the first one you can create object of Class1 (or any other class if present in Class1) and invoke the methods
With the second one you can directly call the static methods of Class2 without referencing it with classname
Updated
See tutorials on packages in JAVA

Learning Java - importing and packages basics

I'm reading every tutorial I can find as well as a book, still trivial concetps leave me asking questions:
CLASSPATH is a variable registered with the JVM that tells java the root directory in which to start looking for classes/jars/etc?
import is similar to include (C/C++) but provides a namespace via package? I just read how without using import you have to explicitly state the package/namespace for every class (using the FQCN) such as java.util.String (possibly invalid excuse) where as using import java.util would allow me everywhere else in the code to simply refer to class as String.
What confuses me about import is some examples use import like:
import java.util.*; // import all public classes from java.util package
import java.util.Hashtable; // import only Hashtable class (not all classes in java.util package)
Yes the article also follows up:
Note that we can call public classes stored in the package level we do the import only. We can't use any classes that belong to the subpackage of the package we import. For example, if we import package world, we can use only the HelloWorld class, but not the HelloMoon class.
So which is it, when I use the * in an import is that not recursively importing all sub-packages?
7.5.2. Type-Import-on-Demand Declarations
import java.util.*;
causes the simple names of all public types declared in the package java.util to be available within the class and interface declarations of the compilation unit. Thus, the simple name Vector refers to the type Vector in the package java.util in all places in the compilation unit where that type declaration is not shadowed (§6.4.1) or obscured (§6.4.2).
The declaration might be shadowed by a single-type-import declaration of a type whose simple name is Vector; by a type named Vector and declared in the package to which the compilation unit belongs; or any nested classes or interfaces.
The declaration might be obscured by a declaration of a field, parameter, or local variable named Vector.
(It would be unusual for any of these conditions to occur.)
You are correct.
Unlike C/C++ include, Java's import is optional, as Java loads all classes it finds in CLASSPATH regardless.
Java's import statements allows you to alias commonly used classes so you don't have to fully qualify them each time.
Let's say you have the following class defined:
package com.foo.bar;
public class Bazz {
public static final int ONE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
... some methods ...
}
There are several ways of using import:
import com.foo.bar.*; // import all classes belonging to package com.foo.bar, and com.foo.bar only.
import com.foo.bar.Bazz; // import class com.foo.bar.Bazz only
import static com.foo.bar.Bazz.*; // import all static constants in class com.foo.bar.Bazz
import static com.foo.bar.Bazz.ONE; // import static constant com.foo.bar.Bazz.ONE only
As you state, there is no way of recursively importing packages.
As an aside, most IDEs will auto-import the classes for you. For example, Eclipse does this when you press CTRL+SHIFT+O.
As in the example you provided in the question, when you specify
import java.util.*;
You import all of the public classes in the java.util package. You do not import any public classes that reside outside the java.util package.
Integrated development environments (IDE) like Eclipse will create individual class imports for you. There's not much reason to code a global import (with an asterisk) any more.
Yes. That's what it does.
But it is best practice to provide absolute path in the import statement.

Categories