3

How can I make the following work:

class Foo extends javax.swing.undo.UndoManager {
  // increase visibility - works for method
  override def editToBeUndone: javax.swing.undo.UndoableEdit = super.editToBeUndone

  // fails for field
  def edits: java.util.Vector[javax.swing.undo.UndoableEdit] = super.edits
}

Note that edits is a protected field in CompoundEdit (a super class of UndoManager). I would like to have a public accessor with the same name that reads that field. How would I do that?

<console>:8: error: super may be not be used on variable edits
         def edits: java.util.Vector[javax.swing.undo.UndoableEdit] = super.edits
                                                                            ^
0__
  • 66,707
  • 21
  • 171
  • 266

2 Answers2

2

Well, there's always reflection.

class Foo extends javax.swing.undo.UndoManager {
  def edits(): java.util.Vector[javax.swing.undo.UndoableEdit] =
    classOf[javax.swing.undo.CompoundEdit].
    getDeclaredField("edits").get(this).
    asInstanceOf[java.util.Vector[javax.swing.undo.UndoableEdit]]
}

You can also disambiguate the two calls by nesting, though this is ugly:

class PreFoo extends javax.swing.undo.UndoManager {
  protected def editz = edits
}
class RealFoo extends PreFoo {
  def edits() = editz
}

You do need the (), though--without it conflicts with the field itself (and you can't override a val with a def).

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
1

You can't change the visibility of an inherited field, this is not allowed.

In some case you could 'simulate' such behavior by using composition, but you won't be able to implement the CompoundEdit class obviously.

Not sure about 'editToBeUndone' as this method doesn't exist in the class: http://docs.oracle.com/javase/6/docs/api/javax/swing/undo/CompoundEdit.html

Alois Cochard
  • 9,812
  • 2
  • 29
  • 30
  • Sorry, `editToBeUndone` is in `UndoManager` (this is the class I'm actually extending). Anyway. Since I can add a method named `edits`, I just wonder, is there any trick to refer to the field `edits` through some qualification, instead of trying `super.edits`. – 0__ Mar 23 '13 at 20:59