Why cant I create the object of Console class? - java

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.

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().

System.out.println(); Implementation

Can anyone here tell me how System.out.println() is implemented? I have tried many sites but didn't get any satisfactory answer.
In System.out.println,
System is a final class.
out is object of PrintStream class inside system.
println() is a method of PrintStream
So to print something we need to call a println which is inside PrintStream class whose object is inside System class.Hence
System.out.println();
For more information refer following
link

How Console reference variable refers to some other class method

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.

Constructor Console() is not visible

I get the feeling once someone answers this question, I will feel a little stupid.
Regardless, I just downloaded Java 7.5 and I am immediately a encountering problem that did not exist before the download.
I was about to write a quick program to do something. To do what is, for once definitely, irrelevant. I set about starting this by initiating the console.
Literally all I had written was:
public static void main(String[] args)
{
Console console = new Console();
}
I encountered this error
The constructor Console() is not visible
Before I updated Java, I had only encountered this due to my own error.
Has the Console constructor's modifier been changed in this update? I'm assuming not.
If the Console class has been changed, what is the correct syntax now?
Read the javadoc for this kind of information. It will tell you there is in fact no visible constructor, and that an instance "can be obtained by invoking the System.console() method".
You need to invoke System.console() to retreive the object:
You should use: Console con = System.console();
public final class Console
extends Object
implements Flushable
http://docs.oracle.com/javase/7/docs/api/index.html?java/io/Console.html

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().

Categories