fre.sch
fre.sch

Reputation: 33

Member Access in Java

I have code where a variable name is identical to the class name. I.e.:

class Foo {
  static public void main(String[] args) {
    Integer Foo;
    Foo.main(args);
  }
}

How can I call the main-method without renaming the variable or the class?

Upvotes: 0

Views: 236

Answers (5)

user207421
user207421

Reputation: 311023

I have code where a variable name is identical to the class name

Why? The simple answer is "don't". The convention is that class names start with a capital and member variable names don't, which takes care of it completely.

Upvotes: 0

gtiwari333
gtiwari333

Reputation: 25164

use the full package name, it works.

package my.pck;
class Foo {
    static public void main(String[] args) {
        Integer Foo;
        my.pck.Foo.main(new String[] { "arg" });
    }
}

But why would you want to call main from main like that? its creating infinite loop.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234847

If class Foo is in a package, you could use the fully qualified name:

my.package.Foo.main(args);

You could also rename variable Foo; it's bad Java style to capitalize variable names. Finally, why would you want to call main from main like that? It's going to overflow the stack very quickly.

Upvotes: 3

Since Integer does not have a main(...) method, this is not a problem.
More generally speaking, if you need to disambiguate, use the full package name.

Upvotes: 1

If it's not in the default package you could refer to it via the package name also, e.g.:

packagename.Foo.main(args);

or you can simply refer to main without the class name, e.g.:

main(args);

Upvotes: 9

Related Questions