Question

I started working with PrintDocument object in WinForms in order to do some printing.

I noticed something very strange about that object. In it there is a property called DefaultPageSettings, and in that property their is a property called PrinterSettings an so on. I can write:

PrintDocumet.DefaultPageSettings.PrinterSettings.DefaultPageSettings.PrinterSettings.DefaultPageSettings.PrinterSettings

and continue forever without getting into a NULL object. Can someone please explain why is this?

Was it helpful?

Solution

This is very simple crossreference really, you can easily build it by having two objects that refer to each other. It's not necessarily a good idea, but sometimes design ideals (like it may cost too much to redesign an old application to behave more reasonably in reference to the new one you're building) drive you into a situation where you're just stuck with it.

public class Foo {
  private Bar bar;

  public Foo(Bar bar) {
    this.bar = bar;
  }

  public Bar getBar() {
    return bar;
  }
}

public class Bar {
  private Foo foo;

  public void setFoo(Foo foo) {
    this.foo = foo;
  }

  public void getFoo() {
    return foo;
  }
}

public class FooBarTest {
  public static void main (String[] args) {
    Foo foo = new Foo();
    Bar bar = new Bar(foo);
    foo.setBar(bar);

    foo.getBar().getFoo().getBar().getFoo()...
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top