Android efficiency importing static methods or importing the class - java

I've seen in some projects people importing directly a static method into an Activity or a class instead of the whole class.
My question is, knowing that a static method can be called several times (for being more accurate, 5 or more times) in the same class, is it more efficient to import the static method or it is better to call it through its class?

Your question (according to me) does seems to address the same point.
The question is if:
is calling ClassName.staticMethod() directly
or this
import static ClassName.staticMethod;
//rest of the stuff
staticMethod();
In both cases, the methods are loaded as a singleton whenever the class is called first.If you import the static method,then thats the first time or else when you use the class's method.
So it wont make a difference because the JVM/DVM (not sure about ART) already has the data required.
IF however your question is regarding what modifiers to use,then this advocates static.
But as mentioned,involving static methods directly is just messy.
So now its more of a personal choice.
Read as:Do not import static methods directly unless you have a very specific reason to do so.

There is no difference in performance between static imports and import the class.
However, import the class and use the class name to call static methods is considered a better practice, because the code is more easy to read. With static imports it could be a bit confusing which methods are non-static methods of the class and which methods are static methods of other classes.

Related

Unique methods for use through the class rather than an object

So, I'm beginning to learn Java and I think it's an awesome programming language, however I've come across the static keyword which, to my understanding, makes sure a given method or member variable is accessible through the class (e.g. MyClass.main()) rather than solely through the object (MyObject.main()). My question is, is it possible to make certain methods only accessible through the class and not through the object, so that MyClass.main() would work, however MyObject.main() would not? Whilst I'm not trying to achieve anything with this, I'd just like to know out of curiosity.
In my research I couldn't find this question being asked anywhere else, but if it is elsewhere I'd love to be pointed to it!
Forgive me if it's simple, however I've been thinking on this for a while and getting nowhere.
Thanks!
Any static method or member belongs to the class, whereas non-static members belong to the object.
Calling a static method (or using a static member) by doing myObject.method() is actually exactly the same as MyClass.method() and any proper IDE will give a suggestion to change it to the second one, since that one is actually what you are doing regardless of which of the two you use.
Now to answer the actual question:
is it possible to make certain methods only accessible through the class and not through the object
No, not as far as i know, but like I said, any proper IDE will give a warning, since it makes little sense and it gives other readers of the code an instant hint that you're dealing with static members.
Yes, short answer is no.
But you can put your static members in a dedicated class, so that no instances share any one of them.
MyObject is instance of MyClass, and you aggregate all you static parts in MyStaticThing.
Using static member on an instance can be misleading, so it is a bad practice
http://grepcode.com/file/repo1.maven.org/maven2/org.sonarsource.java/java-checks/3.4/org/sonar/l10n/java/rules/squid/S2209.html
While it is possible to access static members
from a class instance, it's bad form, and considered by most to be
misleading because it implies to the readers of your code thatthere's
an instance of the member per class instance.
Another thing, do not use static things, because you cannot do abstraction and replace implementations to extend your code.
Being able to switch between implementations is useful for maintenance and tests.
In Java, you can crete an object with these keywords.(new keyword, newInstance() method, clone() method, factory method and deserialization) And when you create an object,it can also use classes abilities which is like static methods.
Short answer:No.
Is it possible to make certain methods only accessible through the class and not through the object?
Yes, it is. You achieve this by preventing any instances of the class to ever be created, by making the class non-instantiable: declare its constructor private.
public final class NonInstantiable {
private NonInstantiable() {
throw new RuntimeException(
"This class shouldn't be instantiated -- not even through reflection!");
}
/* static methods here... */
}
Now, it only makes sense to declare any methods of the class static -- and they can only be called through the class name. Such a class is often called a utility class.

Designing Helper/Utility classes - java

Maybe this question is general but I did not find an answer I was looking for, so I was hoping to get some ideas from this post. I am trying to move out some commonly used methods to a helper to simplify my design. I looked at multiple posts and debate about making the utility methods static v/s non-static. My question is more related to creating a helper classes with a combination of static and non-static methods. Since the existing class contains a combination of static and non-static methods that I want to move out as I do not want duplicate code in multiple classes. So, I was wondering if it is a good idea to include both static and non static methods in the helper class. The reason I am a little hesitant is most utility methods are static in nature and I want to understand if it a good design choice to have static and non-static methods in utility classes. Any suggestions??
It depends on what the class is doing.
Non-static methods imply that the helper class maintains some state that can be different across different instances. If you don't have that then all static methods is the way to go (think like the java Math or Collections classes).
If you need to maintain instance state across method calls, then non-static methods are useful. If you go in this direction, then your helper class will have constructors or static factory methods that create Helper objects and each instance will have fields that maintain state.
non-static methods might also be a good idea if your otherwise static methods often have the same parameters over and over again that are all the same values/references. In that case it might be cleaner to make those constructor parameters and just have the method parameters for the additional parameters that differ between the methods.

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

java static import

sometimes we can from ClassA do :
import com.software.ClassB;
classbObject = new ClassB ;
ClassB.getMethodX();
and we can also from ClassA make directly
import com.software.ClassB;
classbObject = new ClassB ;
classbObject.getMethodX();
what is the diffrence between these 2 cases (calling directly the class or the object)? is there one recommended?
thanks,
If you mean the same thing as I mean: no, there is no functional difference between ClassB.getMethodX() and classbObject.getMethodX() since the getMethodX is static. Only your compiler may give you a warning that classbObject.getMethodX() is discouraged because of the static method call from a non-static context.
You mean why this :
ClassB.getMethodX()
is different from this?
classbObject.getMethodX()
If so, then the second is somehow wrong. I mean it still works, but it makes no sense. The method is declared as static, which "belongs" to the class. You have one static method for a class, not matter how many instances. So, every static method should be called in a static way:
ClassB.getMethodX()
The only way you can do ClassB classbObject without an import is if they are in the same package. If you are asking, should you use an import the answer is, use an import if it is required because the class is not in the same package.
I don't see a static import in your question so not sure how that relates to your question.

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 )
}

Categories