roverred
roverred

Reputation: 1921

Java: How to create new class object for Reader class from java.io when it has protected constructor

I wanted to create a new class object for java's Reader class, but I can't access the constructor since it is protected.

Reader Class Description

Reader myReader = new Reader(); 

Will not work.

Normally, I would create a new function that class to access that constructor, but since the function is a part of java default library, how do I access it? Thanks for any help.

Upvotes: 3

Views: 10044

Answers (4)

basiljames
basiljames

Reputation: 4847

If you check the Reader Java Doc you can see the concrete subclasses of Reader intialyze any one of them based on your requirement. You cannnot instantial Reader as it is abstract

BufferedReader
CharArrayReader
FilterReader
InputStreamReader
PipedReader
StringReader

Upvotes: 1

scarcer
scarcer

Reputation: 233

As others said, you may create a instance of subclass of Reader, such as BufferedReader.

If you don't want to use subclass of Reader, you may create instance of Reader like below

Reader reader = new Reader() {

        @Override
        public int read(char[] cbuf, int off, int len) throws IOException {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public void close() throws IOException {
            // TODO Auto-generated method stub

        }};

Upvotes: 3

Paul Bellora
Paul Bellora

Reputation: 55233

Reader is an abstract class, so you must instantiate an implementation of it, such as BufferedReader or InputStreamReader.

Upvotes: 4

Thilo
Thilo

Reputation: 262834

Reader is an abstract class. You cannot instantiate it, only for the purposes of making a subclass instance.

Did you mean

Reader myReader = new InputStreamReader(in, "UTF-8");

Upvotes: 6

Related Questions