Why System class doesn’t requires instantiation? [duplicate] - java

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.

Related

Why is the Final modifier used in anonymous blocks when referencing a local variable from the main class [duplicate]

This question already has answers here:
Why are only final variables accessible in anonymous class?
(15 answers)
Cannot refer to a non-final variable inside an inner class defined in a different method
(20 answers)
Closed 7 years ago.
final JTextField jtfContent = new JTextField();
btnOK.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event){
jtfContent.setText("I am OK");
}
} );
If I omit final, I see the error "Cannot refer to a non-final variable jtfContent inside an inner class defined in a different method".
Why must an anonymous inner class require the outer classes instance variable to be final in order to access it?
Well first, let's all relax, and please put that gun down.
OK. Now the reason the language insists on that is that it cheats in order to provide your inner class functions access to the local variables they crave. The runtime makes a copy of the local execution context (and etc. as appropriate), and thus it insists that you make everything final so it can keep things honest.
If it didn't do that, then code that changed the value of a local variable after your object was constructed but before the inner class function runs might be confusing and weird.
This is the essence of a lot of the brouhaha around Java and "closures".
Note: the opening paragraph was a joke in reference to some all-caps text in the original composition of the OP.
The methods in an anonymous class
don't really have access to local
variables and method parameters.
Rather, when an object of the
anonymous class is instantiated,
copies of the final local
variables and method parameters
referred to by the object's methods
are stored as instance variables in
the object. The methods in the object
of the anonymous class really access
those hidden instance variables. [1]
Thus, the local variables and method parameters accessed by the methods of the local class must be declared final to prevent their values from changing after the object is instantiated.
[1] http://www.developer.com/java/other/article.php/3300881/The-Essence-of-OOP-using-Java-Anonymous-Classes.htm
The variables around the definition of the class live on the stack, so they are probably gone when the code inside the inner class runs (if you want to know why, search stack and heap). That's why inner classes don't actually use the variables in the containing method, but are constructed with copies of them.
This means that if you change the variable in the containing method after constructing the inner class, its value won't change in the inner class, even though you'd expect it to. To prevent confusion there, Java requires them to be final, so you expect not to be able to modify them.
The reason is that Java do not fully support so-called "Closures" - in which case the final would not be necessary - but instead have found a trick by letting the compiler generate some hidden variables which is used to give the functionality you see.
If you disassemble the generated byte code you can see how the compiler does it, including the strangely named hidden variables containing copies of the final variables.
It is an elegant solution to give functionality without bending the language backwards to do so.
Edit: For Java 8 lambdas give a more concise way to do what was previously done with anonymous classes. The restrictions on variables have also loosened from "final" to "essentially final" - you do not have to declare it final, but if it is treated like it is final (you could add the final keyword and your code would still compile) it can be used. This is a really nice change.
Since Java 8 final modifier is optional for outer instance variables. Value should be 'effectively final'. See answer Difference between final and effectively final.

What exactly are and when are static methods/variables used? [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 8 years ago.
I'm quite new to Java and I'm trying to understand static variables and methods. Could someone give me a brief explanation of why I'd use the static method over the instance method and also what would be the ideal situation to use static variables? I know that static variables and methods are part of the class and not an instance of said class but I'm having trouble understanding when I'd use it.
Thanks!
These are the main differences
1.Static variables take memory only 1 time during the lifetime of program.
2.You can call static variables or methods. without creating the object of that class by classname only.
3.Static variables can be called in static and non-static context.
Mainly static variables are used to save memory because every object takes memory .
Static members relate to a type not a concrete instance. So instance methods and variables concern the identity of the instance, e.g. an instance method can alter the state of the object.
To some extend this is a religious question. Some people prefer to create static methods in a class when they do not access any instance variable. Other people do not like this approach. Another usual usage is creating factory methods, able to create an instance of an object while itself being called statically.
Often there are utility classes that contain static methods to serve clients with some functionality that is not bound to any type context. But all too often these utility classes get abused by using them as a trash bin for all sorts of methods a programmer did not find a fitting class for. This may be a result of poor design.
A popular use of static variables is the definition of an logger instance (e.g. SLF4J) for a class because loggers are thread safe and can be used by all instances and static methods alike. One advantage is (see a comparison) that only one instance has to be created for all instances of the containing class.
For static variable or method, you can think of that there is only one copy of the variable or method during the whole life time of the program.
So if you there is variable whose value should be shared across all the processes or thread, you can declare a static variable. For example, when you want to use a singleton pattern, you will need a static variable to indicate if there is instance of the class already.
For static methods, I would use them when state of the class is not important. I think the best example is java.lang.Math, they are all static methods, and returns the expected values to you no matter what you called before.

Why final classes cannot be overridden in java? [duplicate]

This question already has answers here:
What is the point of "final class" in Java?
(24 answers)
Closed 9 years ago.
I was asked about the reason of why a final class cannot be overridden. I tried to explain that it is more of design approach where by you don't want your class to be extended or methods to be overridden and a final class also helps to make an object immutable (though there are more steps to be done rather than just declaring the class as final).
However I would like to know if there is more to thought process behind declaring a class as final or the fact that it cannot be overridden?
Because them's the rules; It's a part of the design of the language.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.1.2
As a designer you say "my class is not suitable for inheritence"; Java honours this by explicitly preventing someone from doing so.
Final class cannot be extended because Java compiler will not allow it, because Java compiler follows the rules defined by Java Language Specification which does not allow it.
final methods can't be overriden, because that's what final is designed to do: it's a sign saying "do not override this".
From Wiki
A final method cannot be overridden or hidden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
A common misconception is that declaring a class or method as final improves efficiency by allowing the compiler to directly insert the method wherever it is called (see inline expansion). But because the method is loaded at runtime, compilers are unable to do this. Only the runtime environment and JIT compiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.
A final class is a class that can't be extended, thats the reason u cannot override the final class
it is also used to make the class immutable
and one good advantage of defining class as final that it improves JVM performance
see this

java static keyword

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.

Why Java inner classes require "final" outer instance variables? [duplicate]

This question already has answers here:
Why are only final variables accessible in anonymous class?
(15 answers)
Cannot refer to a non-final variable inside an inner class defined in a different method
(20 answers)
Closed 7 years ago.
final JTextField jtfContent = new JTextField();
btnOK.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event){
jtfContent.setText("I am OK");
}
} );
If I omit final, I see the error "Cannot refer to a non-final variable jtfContent inside an inner class defined in a different method".
Why must an anonymous inner class require the outer classes instance variable to be final in order to access it?
Well first, let's all relax, and please put that gun down.
OK. Now the reason the language insists on that is that it cheats in order to provide your inner class functions access to the local variables they crave. The runtime makes a copy of the local execution context (and etc. as appropriate), and thus it insists that you make everything final so it can keep things honest.
If it didn't do that, then code that changed the value of a local variable after your object was constructed but before the inner class function runs might be confusing and weird.
This is the essence of a lot of the brouhaha around Java and "closures".
Note: the opening paragraph was a joke in reference to some all-caps text in the original composition of the OP.
The methods in an anonymous class
don't really have access to local
variables and method parameters.
Rather, when an object of the
anonymous class is instantiated,
copies of the final local
variables and method parameters
referred to by the object's methods
are stored as instance variables in
the object. The methods in the object
of the anonymous class really access
those hidden instance variables. [1]
Thus, the local variables and method parameters accessed by the methods of the local class must be declared final to prevent their values from changing after the object is instantiated.
[1] http://www.developer.com/java/other/article.php/3300881/The-Essence-of-OOP-using-Java-Anonymous-Classes.htm
The variables around the definition of the class live on the stack, so they are probably gone when the code inside the inner class runs (if you want to know why, search stack and heap). That's why inner classes don't actually use the variables in the containing method, but are constructed with copies of them.
This means that if you change the variable in the containing method after constructing the inner class, its value won't change in the inner class, even though you'd expect it to. To prevent confusion there, Java requires them to be final, so you expect not to be able to modify them.
The reason is that Java do not fully support so-called "Closures" - in which case the final would not be necessary - but instead have found a trick by letting the compiler generate some hidden variables which is used to give the functionality you see.
If you disassemble the generated byte code you can see how the compiler does it, including the strangely named hidden variables containing copies of the final variables.
It is an elegant solution to give functionality without bending the language backwards to do so.
Edit: For Java 8 lambdas give a more concise way to do what was previously done with anonymous classes. The restrictions on variables have also loosened from "final" to "essentially final" - you do not have to declare it final, but if it is treated like it is final (you could add the final keyword and your code would still compile) it can be used. This is a really nice change.
Since Java 8 final modifier is optional for outer instance variables. Value should be 'effectively final'. See answer Difference between final and effectively final.

Categories

Resources