Why did my import fail in Java? - 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

Related

Cant use a public method from another class in java

I am trying to call a public constructor of a public class located in one package of my project from the main class, located in a class from another package different to the first one, but located in the same project.
I have understood that the public modifier grant you access to methods from any location inside or outside the package, so i just try to create and instance a new object of the public class first mentioned.
F.E: I try something like.... ClassName newObject = new ClassName(); from the main class
Actually, in order to be able of using that (im using netbeans IDE) I need to import the class/method I want to call, even if they have the public modifier.
My question is... is there a way of using these methods without the need of importing them to the main class ?
I am new in this webpage, so sorry if there is anything wrong with the question.
Qualification and visibility have little to do with eachother. Those are different concepts.
Visibility (enforced by access modifiers like public, protected, private and package-private) is about which class may access (i.e. call or use) it.
Qualification is about the compiler asking you: "Okay, you are mentioning a class name, but there could be thousands around with that name. Which one do you mean?"
You could use the fully qualified class Name instead.
a.b.c.MyClass myClass = new a.b.c.MyClass();
Also see
Java: import statement vs fully qualified name?
Java compiler restricts its search for classes inside the package only. In order to make use of any class belonging to a different package, you have to import it explicitly. You can read more about packages here.
Access specifiers are more from restricting the methods from being accessible by outside world. These access specifiers enforce further restrictions on top of what is enforced by packages. You can refer to this link for access specifiers.

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}

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

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 : Accessing a class within a package, which is the better way?

If I access a class within a package using fully qualified name, without importing it, whether it saves any memory?
Using fully qualified class name :
java.lang.Math.sqrt(x);
Import package :
import java.lang.Math;
Math.sqrt(x);
which is the better way : import the package or access using fully qualified name?
Thanking you..
There is no performance difference between importing the package or using the fully qualified class name. The import directive is not converted to Java byte code, consequently there is no effect on runtime performance. The only difference is that it saves you time in case you are using the imported class multiple times. This is a good read here
No, it doesn't save you memory.
Also note that you don't have to import Math at all. Everything in java.lang is imported automatically.
A better example would be something like an ArrayList
import java.util.ArrayList;
....
ArrayList<String> i = new ArrayList<String>();
Note I'm importing the ArrayList specifically. I could have done
import java.util.*;
But you generally want to avoid large wildcard imports to avoid the problem of collisions between packages.
They're equivalent. The access is the same.
The import is just a convention to save you from having to type the fully-resolved class name each time. You can write all your Java without using import, as long as you're a fast touch typer.
But there's no difference in efficiency or class loading.
As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang package is automatically imported, as is everything in the current package.
The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.
By the way, if you are using lots of static methods (from Math, for example), you could also write
import static java.lang.Math.*;
and then use
sqrt(x)
directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)
Import package is for better readability;
Fully qualified class has to be used in special scenarios. For example, same class name in different package, or use reflect such as Class.forName().

Categories