I know the definition of static which is a keyword to refer a variable or method to the class itself. Could this mean if I wrote a method called parseInt() in a class called calculator and another method called parseInt() in a different class called mathProgram, the compiler Eclipse will know which class the method parseInt() is referring to?
You need to call static methods by referencing the class it is a part of:
MathProgram.parseInt();
Is not the same as
Calculator.parseInt();
So written this way it is clear to the JVM which method you were referring to.
Edit: You can also call static methods using an instance variable but this is in bad form and should be avoided. See this SO answer for more info.
Edit2: Here's a link to the Java Coding Conventions section regarding the use of calling static methods from instance variables. (Thanks to Ray Toal for the link left in the answer to a question posted here)
Yes, because static methods and variables must be in a class and to call them outside of that class you need to qualify them.
For example Calculator.parseInt() and OtherClass.parseInt().
Eclipse uses that to tell them apart.
If the method is static, you need to call it using the classname:
Calculator.parseInt();
Otherwise, with an instance:
Calculator c = new Calculator();
c.parseInt();
Either way, its explicit which you want.
Related
This question already has answers here:
out in System.out.println()
(8 answers)
Closed 1 year ago.
Firstly sorry if this a very basic question but someone ask me this and i don't have any answer.
In the statement
System.out.println()
System is a class in java.lang package, out is a static variable of System class and println() is an overloaded method.
Then Why System class doesn’t requires instantiation?
Thanks
java.lang.* is imported by default, i.e. all classes in the java.lang.* package are accessible by your program. So, your class has access to the members of the System class, among which is out, a static field of type PrintStream. Static members are not tied to an instance of the class, and so they can be accessed directly without instantiation. Hence, you are able to call the overloaded print methods available to out.
If you declare a static method in a Java class you don't need to create an object but simply invoke the method like System.out.println().
The System class cannot be instantiated anyway (cf. Javadoc).
This is achieved by setting the constructor to private:
private System() {
}
However, the System class in openj9 for example is partially filled by call of the afterClinitInitialization() method, which is called after thread initialization.
In there, the out Variable is actually initialized:
setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)), true));
See:
System.afterClinitInitialization()
Thread.initialize()
After that it stops being traceable via Github, but I guess you get the point. The initialization is just done by the JVM and due to out being static, no instance of System is needed to access the variable.
The topic of static variables however is well covered:
What does the 'static' keyword do in a class?
Static (Keyword) - Wikipedia.com
And to fully understand that, you must have a decent knowledge of the JVM and native programming, where I have to surrender myself.
I'm writing an explanation for some code for a course, and have been accidentally using the words method and function interchangeably. I decided to go back over and fix the wording, but ran into a hole in my understanding.
From what I understand, a subroutine is a function if it doesn't act on an instance of a class (its effect is restricted to its explicit input/output), and is a method if it operates on an instance of a class (it may carry out side effects on the instance that make it impure).
There's a good discussion here on the topic. Note that by the accepted answer's definitions, a static method should actually be a function because an instance is never implicitly passed, and it doesn't have access to any instance's members.
With this is mind though, shouldn't static methods actually be functions?
By their definition they don't act on particular instances of a class; they're only "tied" to the class because of relation. I've seen a few good looking sites that refer to static subroutines as "methods" though (Oracle, Fredosaurus, ProgrammingSimplified), so either they're all overlooking the terminology, or I'm missing something (my guess is the latter).
I'd like to make sure I am using the correct wording.
Can anybody clear this up?
This quote from 8.4.3.2 may help:
A method that is declared static is called a class method.
A method that is not declared static is called an instance method [...].
Class methods: associated with a class.
Instance methods: associated with an instance.
Java just wants you to "think object-oriented". Also, static methods have access to a surrounding scope which may include state. In a way, the class is like an object itself.
The simple answer is that when Java decided to call everything a "method", they didn't care about the distinction between a function and a method in theoretical computer science.
Static methods are not exactly functions, the difference is subtle, but important.
A static method using only given input parameters is essentially a function.
But static methods may access static variables and other static functions (also using static variables) so static methods may have a state which is fundamentally different to a function which are by definition stateless.
(ADDENDUM: While programmers are often not so strict with using "function" as definition, a strict function in computer science can access only input parameters). So defining this case of accessing static fields it is not valid to say that static methods are always functions.
Another difference which justifies the usage of "static method" is that you can define in C derivates global functions and global variables which can be accessed everywhere. If you cannot access the class which contain static methods, the methods are inaccessible, too. So "static methods" are limited in their scope by design in contrast to global functions.
In Java, a user-defined class is actually an instance of a subclass of java.lang.Class.
In this sense, static methods are attached to an instance of a conceptual class: they are attached to an instance of a subclass of java.lang.Class.
With this in mind, the term "class method" (an alternate name for Java's static methods) begins to make sense. And the term "class method" can be found in many places: Objective C, Smalltalk, and the JLS -- to name just a few.
In computer science function clearly maps to a static method. But "method" of a class is a bit generic, like "member" (field member, method member). There are wordings like
Data members and method members have two separate name spaces: .x and .x() can coexist.
So the reason is, that as the philosoph Ludwig Wittgenstein said, Language is a tool with different contexts. "Method" is a nice moniker in the citation above to categorize a "member".
Your thinking is right and it makes sense. It's just not established terminology in the Java community. Let me explain some internals that can help understand why the terminology subsists.
Java is a class based object oriented language. A method is always member of a class or instance (This is a general statement valid for other programming languages too). We think of class and instance being both objects.
Instance method (dynamic)
You cannot invoke this method from a class directly, you have to create an instance. Each instance references that method. You can overwrite a method definition with the exact same method signature (when subclassing), i.e. the reference points to a different method (which has the same signature, but can have a different method body). The method is dynamic.
Class method (static)
You only can invoke this method from the class directly, i.e. you don't need to create an instance of that class. There is only one global definition of that method in the whole program. You cannot overwrite the exact same method signature when the method is declared static, because there is only one definition valid for the whole program. Note that the method is member of the class object itself, the instances have all the same unique (and fix) reference to that method.
Here is another take on the terminology, using Scala as a mnemonic:
In Scala you have objects, which are singleton instances of an implicitly defined class 1.
Per your definition, we can call these subroutines belonging to the object methods, as they operate on a single instance of the class.
Additionally the object will also define class A, and create all of the methods in object A as static methods on class A (for interfacing with Java) [2].
Therefore we can say that the static methods of Java class A access the same members as the Scala singleton instance, which per your definition then deserve to be called (static) methods of class A.
Of course, the main difference is - method can use static fields, not only method parameters.
But there is additional one - polymorphism!
Results of evaluation Class A.doTheSameStaticMethod() and ClassB.doTheSameStaticMehod() will be depends of class. In this case function is impotent.
Each class has an object to represent it that is an instance of a subclass of the Class class. Static methods are really instance methods on these objects that are instances of a subclass of Class. They have access to state in the form of static fields, so they are not restricted to being just (stateless) functions. They are methods.
Why do I have to create an instance for the class Scanner, but not for Math class in java?
I hope you guys can explain me this with good examples.
I understand it in this way:
We are asking the same in Math.pow() for examples.
It will always be the power of a number.. (x,y) for example or (x,2)
But .print() or .println() will change the value .. ? That's why we need to create an instance for the class Scanner.. am I right?
Edit: I do know it is static, but I need a more explained in detail answer then.. "its just the way it is"..
Math defines only static methods because it doesn't contain internal states.
You could argue:
But what about polymorphism, what if I want to override Math class?
=> classic mathematical operations are unlikely to be overridden for most of 99% of programs.
So it acts as a simple utility class, waiting for inputs, and outputting some result in one call.
See as an example Math#max:
public static double max(double a, double b)
Since it's static, it means that it's not associated with any object. You can simply call it.
Now look at PrintStream#println:
public void println(boolean x)
Since it's not static, you cannot directly call it by writing PrintStream.println(something).
Think about it, it really make sense that max is static since it doesn't have to be associated with an object, it doesn't really needs an information about an object as it doesn't care about it. It has a well defined behavior for all objects. No special treatment for some objects over others.
Because you are acessing static methods of Math. Note you are using "class i.e. Math".method.
While for Scanner, you use instance as all the methods like nextInt, next are defined as non static.
The constructor for Math is private, meaning you cannot call it from outside Math.
The reason is that it is a class holding a bunch of static utility methods, and there is no need to ever generate an instance of it.
The methods on the Math class are static methods, whereas the ones for the Scanner class are not.
The Scanner class isn't using static methods because each instance needs to maintain their own state, different from other instances of Scanner.
The Math class are simple utility functions that have no state, so they can be static.
I have a question that why main method is marked as public?
According to an answer on stackoverflow, It is declared as static
"The method is static because otherwise there would be ambiguity: which constructor should be called?"
But, can anyone can explain why it is declared public always?
Because the JLS, Section 12.1.4, says so:
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.
If it's not public, then it won't be found; you'll get
Error: Main method not found in class Main, please define the main method as:
public static void main(String[] args)
I believe, the rational behind enforcing main as public is more to do with the language specification – rather than whether something could be achieved or not.
Refer:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1.4
The method main must be declared public, static, and void. It must
specify a formal parameter (§8.4.1) whose declared type is array of
String. Therefore, either of the following declarations is acceptable:
Java uses JNI launch java application will never have any issue in calling a private main – but this is more like jail-brake (like another jail-brake, where reflection API let you access private method) and definitely not in spirit of java specification.
If I remember till JDK 1.3 – it was not mandatory from developer’s perspective. i.e. even a private main was being accepted by JRE. Though, it was not inline with JLS 1.3.
I tried searching JLS 1.3 for a reference, but could not get a link. But I found that it was reported as a bug by developers across world:
Please refer: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4155575
So, a fix was made in subsequent version to enforce rule stated by JLS.
Now, the point is why JLS writer enforced this rule at first place – I really have no idea. The only thing I can think of is that – to keep it “obvious” and non-confusing for developers.
The initialization software that starts your program must be able to see main so that it can call it.
Because that is what is known as the "entry point" and if it is private, your program will not be able to run.
Public - main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application.
From coderanch
When the code is executed, a JVM will be created and that will act as a container for the code we are trying to execute. Declaring this method as public allows the JVM to start the code execution. If method is private, JVM wont be able to call it.
There are ways to call a private method as well (eg by using Reflection), but that is not a standard way to do things.
In Java a function or variable in class in unaccessible untill an Object is created from the class, but the 'main' function is supposed to run at startup(without Object initiation) by JVM. So the 'main' is declared public as well as static so that it can be accessed outside class & without even an Object is created.
Yes the standards say so that main method should be public in Java. But it's not only for Java. However even for C#, main must be public.
So just think about it in real world scenarios.
E.g. you want to enter your room, but you should enter your home main door first (given room is inside the house...and no other means to enter the house)
Main door is the only publicly available access point.
Because the main method should be accessed by JVM without any restrictions from any where. I think you can find more info here: Why main method is public
Util class in java can be made in two ways
class Utils
{
public static ReturnType someUtilMethod(
// ...
}
and execute util method by
Utils.someUtilMethod(...);
Or I can make
class Utils
{
public Utils(){}
public ReturnType someUtilMethod(
// ...
}
and execute util method by
new Utils().someUtilMethod(...)
What way is better? Are some differences between this ways?
Generally Util class contains Utility methods which doesn't need to store the state of Object to process and so static methods are good fit there
A utility function should always be static, unless for some reason it depends on the state of some other variables, and those variables need to be remembered between calls.
The latter should almost never happen, although something like a pseudo-random number generator might be a good case.
The Math functions are a good example of utility functions. When you call Math.sin() the result depends only on the supplied parameter. There is no "state" involved, so there's no need to create an object.
static access will be a better approach as in Util class hold methods which are not concerned with the attributes of the Objects.
Another example will be of Math Class.
Math class has no Instance variables.
And has private constructor, so no object can be created.
So in Math class case using static access like Math.PI is appropriate.
If you use a class that only has static methods, you will not need to instantiate the object everytime you need to use it, saving a line of code and some memory. Just remember to make the default constructor private, so that no one cane inadvertently instantiate it!
A utility class is just a place where to syntactically hold global functions in Java.
Your second example is not covered by the term "utility class". The definition of that concept includes non-instantiability of the class.
The reason to have instance methods would be dynamic method dispatch (to achieve polymorphism), or possibly hold some non-global state. But, as I said, then you would be out of the scope of the term "utility class".