Static means one per Class, not one for each object.
Static means one per Class, not one for each object no matter how many instance of a class might exist, this means that you can use them without creating an instance of a class.
Static method are implicitly final, because overriding is done based on the type of a class and are attached to a class, not on object. static method in a super class can be shadowed by another static method in a sub class, as long as the original method was not declared final. However, you can't override a static method with a non static method.
In other words, you can't change a static method into an instance method in a class.
What is Static Import?
In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say: double r = Math.cos(Math.PI * theta); or System.out.println("Blah blah blah"); You may want to avoid unnecessary use of static class members like Math. and System. For this use static import. For example above code when changed using static import is changed to:
import static java.lang.System.out;
import static java.lang.Math.PI;
import static java.lang.Math.cos;
...
double r = cos(PI * theta);
out.println("Blah blah blah");
...
So whats the advantage of using above technique? 1) readability of the code. 2) Instead of writing name of static class, directly write the method or member variable name. NOTE: Ambiguous static import is not allowed. i.e. if you have imported java.lang.System.out and you want to import mypackage.Someclass.out, the compiler will throw an error. Thus you can import only one member out.
No comments:
Post a Comment