How Console reference variable refers to some other class method - java

I was strucked in a place that i cannot create new instance for Console class. So i took the source code of jdk and then look into it. Then i got cleared that it was declared as "public final class Console........"... So i understood that the final class cannot be instantiated. But that is not my actual doubt. Here in the SCJP Book, i came across a line of code that tells me as Console c = System.console()
Here we cannot create new instance for console class, so creating a reference variable c. Then What is that System.console actually is?? In the book it is told as
Keep in mind that it's possible for your Java program to be running in an environment that doesn't have access to a console object, so be sure that your invocation of System.console() actually returns a valid console reference and not null.
So then i entered to look up source code for System.console().
There i happen to see System as final class and console() as static method inside that.
So how can a Console reference object refer to that console method in system class..
What is the link between these two. I thought of a polymorphic reference.
But that is not because it doesn't pass IS-A Test. So please explain me in detail about this.
Hope my question is clear. Thanks in advance. !

the final class cannot be instantiated
That is wrong , final class cannot be subclassed. It can be instantiated using the new operator if its constructor is visible . I guess Console class has private constructor. Abstract classes cannot be instantited. See the JLS 8.1.1.2:
A class can be declared final if its definition is complete and no subclasses are desired or required.
It is a compile-time error if the name of a final class appears in the extends clause (ยง8.1.4) of another class declaration; this implies that a final class cannot have any subclasses.
System.console()
Returns the unique Console object associated with the current Java virtual machine, if any.
Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.
If this virtual machine has a console then it is represented by a unique instance of this class which can be obtained by invoking the System.console() method.
If no console device is available then an invocation of that method will return null.
console() is some sort of a factory method which gives you back an object of Console associated with the current JVM . The System class has knowledge of the JVM in which it is running and it is the perfect candidate to give you back the Console object.
Console c = System.console();
System.console() gives us back a reference to the Console object and you are assigning the object reference to variable c. This way you can use that reference variable c to access the properties or methods of Console object.

I believe the mistake in your understanding is here:
So i understood that the final class cannot be instantiated
Final classes cannot be extended but can be instantiated. FYI it is the abstract class than cannot be instantiated.

Related

Why doesn't System.out return a null object? [duplicate]

Firstly regrets if this is a very basic question and i promote that I'm still a code monkey.
I was asked in an interview to elucidate System.out.println();
I explained the following way
//this class belongs to java.lang package
class System{
public static PrintStream out;
}
//this class belongs to java.io package
class PrintStream{
public void println..
}
I've explained that System.out is valid since this is the way we access static variables in java, and out is an object of PrintStream and hence we can access its methods, In sum as
System.out.pritnln();
he asked me to simulate a similar kind of program,i traced and it did not work,since System.out is returning null
my question is where is out object instantiated in java ? Is it a predefined object if I'm not wrong. what should be the meticulous explanation for this.
Technically what should we call out? Is out a variable of type PrintStream type or should one say it as an object of type PrintStream ?
System.out is initialized to null when the class is instantiated. This is set by the nullPrintStream() method in System.java, which just returns null.
When the JVM has initialized, it calls the initializeSystemClass() method. This method calls the native method setOut0() which sets the out variable to the appropriate value.
This may seem weird but it is a necessary operation for the following reasons:
out cannot be set statically to the value because System needs to be one of the first loaded classes (before PrintStream).
out must be final so that its value cannot be directly overridden by a user.
Since out cannot be set statically, and is final, we must override the semantics of the language using a native method, setOut0().
I hope that helps your understanding.
System.out is a normal static attribute, it was set by the JVM through the initializeSystemClass() method during JVM initialization. You can even change it (although it's not recommended) by simply calling System.setOut(printOutStream);, where printOutStream is the stream you want to use as standard output.
Here's a nice article detailing how does System.out.println() work.
System.out is provided by the JVM. By the time your main method is called, System.out is open and ready for use.
See http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#out
In the Oracle Java runtime libraries, it is instantiated natively using the registerNatives() native method which is called (via a static initializer) on loading the System class. This is however an implementation detail.
You can also set System.out directly using System.setOut().
Out in System.out.pritln is a static field (object) of PrintWriter in System class and println is a method of PrintWriter.
Reference :
System : http://docs.oracle.com/javase/6/docs/api/java/lang/System.html
PrintWriter : http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html
There is no need to go for net and documentation even. We can simply say javap java.lang.System this gives you list of all static fields, method prototypes that belong to System class.
We can get details of any java class using javap, provided you know its package and classname
out is public static object of PrintStream defined in System class.
When System class get initialized, it calls its initializeSystemClass() method, here is the code:
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
In this code setOut0() is a native function implemented in System.c:
JNIEXPORT void JNICALL
Java_java_lang_System_setOut0(JNIEnv *env, jclass cla, jobject stream)
{
jfieldID fid =
(*env)->GetStaticFieldID(env,cla,"out","Ljava/io/PrintStream;");
if (fid == 0)
return;
(*env)->SetStaticObjectField(env,cla,fid,stream);
}
This is a standard JNI code that sets System.out to the argument passed to it, this method calls the native method setOut0() which sets the out variable to the appropriate value.
System.out is final, it means it cannot be set to something else in initializeSystemClass() but using native code it is possible to modify a final variable.
System.out.println();
here println is an object of printstream class.We can't directly create object for printstream class. Out is an object of system class. out is called field in system class. while calling system.out it indirectly creates object for printstream class. hence we can call println() method using System.out.prontln().

How is it possible to access static variables from a null reference? [duplicate]

This question already has answers here:
How come invoking a (static) method on a null reference doesn't throw NullPointerException?
(5 answers)
Closed 8 years ago.
Recently I was going through a page on javarevisited and found a block of code which asked the readers to determine what would be the output for it...
Though I got the output I am not satisfied with the result (WHICH CAME OUT TO BE "Hello") since I don't know how a static member is accessed from a null reference. What's happening in the background?
public class StaticDEMO {
private static String GREET = "Hello";
public static void main(String[] args) {
StaticDEMO demo = null;
System.out.println(demo.GREET);
// TODO code application logic here
}
}
This works because the JVM knows you are trying to access a static member on a specific class. Because you had to declare demo as a specific class (in this case a StaticDEMO), it knows to use that to find GREET.
To be clear, you don't run into this often (I actually had to type this code in to verify it, I can't say I've ever seen this). Mainly, it's good practice to always refer to static fields by their class, not an object instance (which may be null, as we can see!).
Meaning, prefer this:
System.out.println(StaticDEMO.GREET);
EDIT
I found a reference to this in the Java Specification: Chapter 15, Section 11: Field Access Expressions.
Example 15.11.1-2. Receiver Variable Is Irrelevant For static Field Access
The following program demonstrates that a null reference may be used to access a class (static) variable without causing an exception
[example not shown here for brevity]
Any method which is being decorated as static in Java means, that method is a class level memeber. That means, you do not need an object to accss static members. The static method/variable is maintained by the Class itself, and not by any instance of the class. Here in your example, the compiler already knows that the member is static member and it doesn't need any instance to access that static method.
Static members are stored with the Class, not with any specific instance of it. So, it doesn't matter that the instance is null - the member from the Class is still be accessible.
The JVM simply ignores null, because GREET is a class field and demo is irrelevant reference to refer Class field.
Static method not needed object reference to call it so you can call it even reference to the object is null.

Why cant I create the object of Console class?

I am trying to create an object of Console class, but could not succeed. I am getting this error "The constructor Console() is not visible". I also could not find any constructor in the document. Can anybody explain this?
Jon Skeet's answer is correct: you should use System.console() to get hold of the one instance of Console.
The reason for this is that Console is an implementation of the Singleton design pattern, which is used when the author of an API wants to ensure that one and only one instance of a class is ever created.
You're not meant to create instances directly. Instead, use the System.console() method:
Console console = System.console();
You cannot create a Console object, the constructor is private.
But you can obtain a Console object in this way:
Console console = System.console();
Look at the javadoc for more info.
You dont need to create the object of the Console class. It is not required. Please read below from documentation :
If this virtual machine has a console then it is represented by a
unique instance of this class which can be obtained by invoking the
System.console() method. If no console device is available then an
invocation of that method will return null.
So, you will get the console by System.console() if any console device is available with Virtual Machine.
A Console can't be instantiated explicitely while it's constructor is private. You can access the console associated with the JVM the following way:
Console console = System.console();
See the documentation here.

out in System.out.println()

Firstly regrets if this is a very basic question and i promote that I'm still a code monkey.
I was asked in an interview to elucidate System.out.println();
I explained the following way
//this class belongs to java.lang package
class System{
public static PrintStream out;
}
//this class belongs to java.io package
class PrintStream{
public void println..
}
I've explained that System.out is valid since this is the way we access static variables in java, and out is an object of PrintStream and hence we can access its methods, In sum as
System.out.pritnln();
he asked me to simulate a similar kind of program,i traced and it did not work,since System.out is returning null
my question is where is out object instantiated in java ? Is it a predefined object if I'm not wrong. what should be the meticulous explanation for this.
Technically what should we call out? Is out a variable of type PrintStream type or should one say it as an object of type PrintStream ?
System.out is initialized to null when the class is instantiated. This is set by the nullPrintStream() method in System.java, which just returns null.
When the JVM has initialized, it calls the initializeSystemClass() method. This method calls the native method setOut0() which sets the out variable to the appropriate value.
This may seem weird but it is a necessary operation for the following reasons:
out cannot be set statically to the value because System needs to be one of the first loaded classes (before PrintStream).
out must be final so that its value cannot be directly overridden by a user.
Since out cannot be set statically, and is final, we must override the semantics of the language using a native method, setOut0().
I hope that helps your understanding.
System.out is a normal static attribute, it was set by the JVM through the initializeSystemClass() method during JVM initialization. You can even change it (although it's not recommended) by simply calling System.setOut(printOutStream);, where printOutStream is the stream you want to use as standard output.
Here's a nice article detailing how does System.out.println() work.
System.out is provided by the JVM. By the time your main method is called, System.out is open and ready for use.
See http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#out
In the Oracle Java runtime libraries, it is instantiated natively using the registerNatives() native method which is called (via a static initializer) on loading the System class. This is however an implementation detail.
You can also set System.out directly using System.setOut().
Out in System.out.pritln is a static field (object) of PrintWriter in System class and println is a method of PrintWriter.
Reference :
System : http://docs.oracle.com/javase/6/docs/api/java/lang/System.html
PrintWriter : http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html
There is no need to go for net and documentation even. We can simply say javap java.lang.System this gives you list of all static fields, method prototypes that belong to System class.
We can get details of any java class using javap, provided you know its package and classname
out is public static object of PrintStream defined in System class.
When System class get initialized, it calls its initializeSystemClass() method, here is the code:
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
In this code setOut0() is a native function implemented in System.c:
JNIEXPORT void JNICALL
Java_java_lang_System_setOut0(JNIEnv *env, jclass cla, jobject stream)
{
jfieldID fid =
(*env)->GetStaticFieldID(env,cla,"out","Ljava/io/PrintStream;");
if (fid == 0)
return;
(*env)->SetStaticObjectField(env,cla,fid,stream);
}
This is a standard JNI code that sets System.out to the argument passed to it, this method calls the native method setOut0() which sets the out variable to the appropriate value.
System.out is final, it means it cannot be set to something else in initializeSystemClass() but using native code it is possible to modify a final variable.
System.out.println();
here println is an object of printstream class.We can't directly create object for printstream class. Out is an object of system class. out is called field in system class. while calling system.out it indirectly creates object for printstream class. hence we can call println() method using System.out.prontln().

What "ClassName objectName;" does before the main method?

In this code I see the following lines before the "main" method:
JTextArea displayArea;
JTextField typingArea;
I wonder what these lines do and when they are executed. As far as I know the "main" method is the "entry point". So, the code will be executed from the beginning of the "main" method. All other methods will be executed if they are called from the "main" method. If it is so, the mentioned 2 lines will never be executed. Moreover, even if they will be executed, what exactly they do? What do these pairs of "ClassName objectName" do?
Those are called "declarations". They are declaring the existence of two variables, stating their types and their names. The location of the declaration determines their scope, in other words, which parts of the program are allowed to know about those particular variables, and may refer to them.
Here's a tutorial about Java variables.
You haven't included the whole file.
These are the declarations of fields. It indicates that when the class is instantiated (i.e., an object is created from it), each object will have a reference to a text area and a text field. You will, however, have to create these objects.
Notice how your main method is static. This means that it can run without the containing class being instantiated. However, most Java methods operate on objects. Suppose that your main is in class C. It is likely that somewhere in your main, you will see a "new C" which means that an instance of C is created. Then some other operation will be invoked on that new object (look for other, non-static methods in the file), and these operations will manipulate these two fields.
it specifies the types.
JTextArea displayArea; // this creates textarea type and thus textbox
JTextField typingArea; // thus creates textfield type var and thus text field
These are members (reference) variables of the KeyEventDemo class.
When KeyEventDemo is instantiated using the new keyword, each instance will have a these variables to refer to a JTextArea and JTextField respectively. These are initialized to null and are assigned as references to a couple of instances in the addComponentsToPane method.
Those declarations are evaluated when the object is instantiated by the java virtual machine. That is right before the main methode is this case.
Those are class members.
Basically, in a java class, you have methods and members. The members are variables that hold the state of Objects that are instances of that class.
The main method is separate, it's a static method so it can run without there being an instance of the class. So you have logic that runs in main() and you have logic that runs on an instance of the class. They're quite separate.
If you want too, in your main() function you can create an instance of the class, and then that could would 'run' if there is any initialization of the member functions that needs to be done.
However, not all class members are initialized in the constructor, and those would stay null (so in that case, nothing would 'execute' at that point). In your example, there's no initialization, so those members would be null when the constructor logic starts.

Categories