I have come across a self reference in some code I was looking at.
Example
TestObject selfReference = this;
Is there ever a good case in which you would need a self reference in an object? Is this a sign of a bad coding design or style?
EDIT:
This is an example of where if I use this it will throw an error, but when using selfReference, it compiles.
public class IFrame extends InternalFrame
{
public IFrame()
{
addComponentListener(new java.awt.event.ComponentAdapter()
{
public void componentResized(java.awt.event.ComponentEvent evt)
{
Window.setCurrComponent(this); //compile error
}
public void componentMoved(ComponentEvent evt)
{
Window.setCurrComponent(selfReference); //compiles correctly
}
});
}
}
public class InternalFrame extends JInternalFrame
{
protected InternalFrame selfReference = this;
}
public class Window
{
InternalFrame currFrame;
public static void setCurrComponent(InternalFrame iFrame)
{
currFrame = iFrame
}
}
Yes, there are circumstances in which an implicit self-reference may be entirely natural. Consider, for instance, a circular linked list that currently contains only a single element.
However, having a member variable called selfReference doesn't make any sense at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With