简体   繁体   中英

Why do I get an exception when trying to create a new Console?

import java.io.*;

public class Talk {
    public static void main(String[] args) {
        Console c = new Console();
        String pw;
        System.out.print("password: ");
        pw = c.readLine();
        System.out.println("got " + pw);
    }
}

Please explain to me this compiler exception at console

java:5: error: Console() has private access in Console Console c = new Console(); ^ 1 error

The Console class is obviously not meant to be instantiated directly. You are supposed to use System.console instead:

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.

See the docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM