C# vs. Java: Changing the Behavior of a Method on the Fly

While porting some Java code to C# I ran into a strange feature of the Java language that really surprised me. It’s quite difficult to describe, but basically, in Java you can redefine the behavior of a class method on-the-fly.

Consider this dummy Java code that somewhat resembles the real Java code I was dealing with:

public class Person {
  public String lastName;
  public String firstName;
  
  public Person(String ln, String fn)
  {
    this.lastName = ln;
    this.firstName = fn;
  }
  
  static class Address
  {
    public String street;
    public String city;
    
    public String fullAddress() throws Exception 
    {
      return this.street + " " + this.city;
    }
  }
  
  static Address regularAddress = new Address();
  
  // this call is quite unusual . . . 
  static Address dummyAddress = new Address() {
    public String fullAddress() throws Exception {
      throw new Exception("illegal operation");
    }
  };
  
  public void fooMethod()
  {
    try {
      String ra = regularAddress.fullAddress(); // OK
      System.out.println("fooMethod() successful");
    } catch (Exception e) {
      System.out.println("fooMethod() FAILED");
      e.printStackTrace();
    }
   
  }
  
  public void barMethod()
  {
    try {
      String da = dummyAddress.fullAddress();  // throws
      System.out.println("barMethod() successful");
    } catch (Exception e) {
      System.out.println("barMethod() FAILED");
      e.printStackTrace();
    }
  }
  
} // Person

Class Person contains a nested definition of a class Address. Class Address has a method fullAddress() that gives a street address plus city. The Person class declares two Address objects. The first, regularAddress is nothing unusual. But the second dummyAddress redefines the fullAddress method so that it throws an Exception when called. I could have coded the constructor to do something else if I had wanted to.

CSharpVsJava-RedefiningMethodBehaviorOnTheFly

Very strange. There’s no direct analog in C#. I’d probably either define an abstract class or an interface, and then define two different types of Address classes from the base class / interface.

Advertisements
This entry was posted in Miscellaneous. Bookmark the permalink.