Why it's not possible to named method by a same name in and out a class

class Truc {
  Truc() {}
  void method() {
    method(2) ;
  }
}


void method(int x) {
  println("outside class", x) ;
}

Answers

  • edited July 2016

    Local declarations got priority over external 1s. L-)

    Truc class can freely access all sketch's members b/c it's nested inside it.
    And in turn, the "sketch" is its enclosing class.

    That relationship is called closure. Very famous among JavaScript coders and almost unheard of in Java.

    However, if the nested class defines a member w/ the same name as an external enclosing member, the former overshadows the latter. :-B

  • Answer ✓
    // forum.Processing.org/two/discussion/17643/
    // why-it-s-not-possible-to-named-method-by-a-same-name-in-and-out-a-class
    
    // 2016-Jul-25
    
    void setup() {
      new Truc().anotherName();
      method(MAX_INT);
      exit();
    }
    
    static void method(int x) {
      println("Outside class", x) ;
    }
    
    static class Truc {
      void anotherName() {
        method(-10);
      }
    
      //void method() {
      //  method(2);
      //}
    }
    
  • Answer ✓

    Because it is called (line 4) within the scope of the class, so it will look inside the class for a method with the same signature. That is just part of the Java language specification.

  • ??

    Outside the class:

    just put an object before it:

    car.method(10);

  • It's a pity we cannot do that :( thx for the confirmation.

  • edited July 2016
    • Actually we can access overshadowed members. But in this case we gotta know its datatype.
    • Since I haven't saved my sketch here, its class name is temporarily called sketch_160725c.
    • That's the enclosing class for all of our nested inner classes. And it's the sketch class itself!
    • Now inside inner class Truc, we can access it via sketch_160725c.this.: :)>-

    "sketch_160725c.pde":

    // forum.Processing.org/two/discussion/17643/
    // why-it-s-not-possible-to-named-method-by-a-same-name-in-and-out-a-class
    
    // 2016-Jul-25
    
    void setup() {
      new Truc().method();
      method(MAX_INT);
      exit();
    }
    
    static void method(int x) {
      println("Outside class", x) ;
    }
    
    class Truc {
      void method() {
        sketch_160725c.this.method(2);
      }
    }
    
  • whaouuu...tricky thing. And if I make an application I just need to call the app ?

  • edited July 2016

    Those are just advanced Java stuff. Those knowledge aren't supposed to be put in practice. :-\"

    When creating our own inner classes, why would we pick the same name for a local member when we still need to access the corresponding enclosing member? :-@

Sign In or Register to comment.