View Single Post
Old 03-24-2006, 08:42 PM   #4 (permalink)
destin
Java Junkie
 
destin's Avatar
 
Join Date: Mar 2005
Posts: 40
destin is on a distinguished road
Quote:
Originally Posted by Belisarius
Code:
// Define some example classes

class A {
  public String toString(){
    return "foo";
  }
}

class B {
  public String toString(){
    return "bar";
  }
}

// Define a method in some class

public void print(Object test){
  System.out.println(test);
}

// Put this in your main method

A a = new A();
B b = new B();

print(A);
In Java 5, there is annotation to override methods:
Code:
class A {
    @Override public String toString() {
        return "foo";
    }
}
Personally, I like this. It lets you know when you are actually overriding a method. Prior to this, you would write out the method and wouldn't be sure if you were overriding the method. If, for example, you write toStirng() instead of toString(), the code would compile, but not run as expected. With the override annotation you will receive an error telling you that there is no method toStirng() to override.

@Belisarius
I think you meant that last bit to be print(a);, rather than print(A);.
destin is offline   Reply With Quote