Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4121985

java.io.PrintWriter: Make out a protected field

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P3 P3
    • 1.2.0
    • 1.1, 1.1.8, 1.2.0
    • core-libs
    • None
    • 1.2beta4
    • generic, sparc
    • generic, solaris_2.6
    • Not verified

      Date: Sun, 08 Feb 1998 18:34:42 -0500
      From: Rich Paul <###@###.###>

      I'm having a problem subclassing PrintWriter, and believe that it is an
      inherent flaw in it's design.

      I've got a class called IndentWriter, which is a FilterWriter. For each
      line of text that it outputs, it puts x number of spaces to the left,
      adjustable with increase and decrease methods.

      I'm subclassing PrintWriter, so that I can delegate increase and
      decrease calls to the FilterWriter. Since my 'out' private member has
      to be a FilterWriter, I'd like to do this:

      class PIndentWriter {
          PIndentWriter ( Writer w ) {
              super(new IndentWriter(w));
          };
          void increase ( int i ) {
              ((IndentWriter)out).increase(i);
          };
      };

      This doesn't work, becuase out is private. Since the call to super has
      to be the first call in the method, I can't save the IndentWriter that
      I'm creating there before calling super. Since ( at least in JDK1.2 ) I
      can't add a field called dOut, and say
              super(dOut=new IndentWriter)
      I have been left doing this:

      class DummyPrintStream extends PrintStream {
          protected IndentWriter dOut;
          DummyPrintStream ( IndentWriter iw ) {
              super(iw);
              dOut = iw;
          };
      };

      class PIndentStream extends DummyPrintStream {
          IndentWriter wrap ( Writer w ) {
              if ( w instanceof IndentWriter ) {
                  return w;
              } else {
                  return new IndentWriter(w);
              };
          };
          PIndentStream ( Writer w ) {
              super(wrap(w));
          };
      }

      This gives me what I need, but at a cost of creating an entirely new
      class, and carrying a new pointer, and adding a static support method.

      As I write, I am thinking that I could probably add another overloaded
      constructor, which takes an IndentWriter, and saves it's paramater after
      calling super(), and then call this(wrap(w)) in my other constructors,
      but that still leaves me with a redundant referance.

      I would suggest making out a protected member of PrintWriter.

            mr Mark Reinhold
            mr Mark Reinhold
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: