Defining method and variable with same name generates inconsistent errors

XMLWordPrintable

    • sparc
    • solaris_2.4

      The following java code compiles and runs, despite a conflict between
      the variable and field both named "foo":

      class Foo {
      public int foo = 10;

      public int foo() {
      return 20;
      }

      public static void main(String argv[]) {
      Foo f = new Foo();
      System.out.println("int foo = "+f.foo);
      System.out.println("int foo() = "+f.foo());
      }
      }

      but, if the variable declaration is moved after the method
      declaration, then it no longer compiles:

      class Foo {
      public int foo() {
      return 20;
      }

      public int foo = 10;

      public static void main(String argv[]) {
      Foo f = new Foo();
      System.out.println("int foo = "+f.foo);
      System.out.println("int foo() = "+f.foo());
      }
      }

      yielding the error:

      Foo.java:6: Duplicate variable declaration: int foo was int foo()
      public int foo = 10;
      ^
      1 error

            Assignee:
            Todd Turnidge (Inactive)
            Reporter:
            Jim Graham
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: