harrybvp
harrybvp

Reputation: 2505

Java - Why is it allowed to have Variable Name as Type Name

Lets Say I have Class ClassA

I can declare a variable as below

public ClassA ClassA;

Note:- Variable name is same as Type Name and There is no compilation error.

This can cause confusion when you want to invoke static method

ClassA.someStaticMethod();

In Above Statement ClassA will be treated as instance variable and if it is null then it is impossible to call static method.

Why is it allowed anyway ?

Are there any Use Cases where this may be beneficial?

Upvotes: 1

Views: 156

Answers (1)

fge
fge

Reputation: 121712

if it is null then it is impossible to call static method.

It is possible:

public final class Foo
{
    public static void yuck()
    {
        System.out.println("Yuck!");
    }

    public static void main(final String... args)
    {
        final Foo foo = null;
        foo.yuck(); // compiles, and does the job
    }
}

Even though it may seem counterintuitive, the fact is that static methods need only know the class; even if an instance of Foo is null, like in the example above, the JVM knows it is of class Foo; yuck() being a static method, it does not "dereference" the instance, because it does not need to; therefore, no NPE.

Why is it allowed?

Because this is a legal Java identifier (JLS, section 6.2). The only restrictions to Java identifiers is that they cannot be keywords.

Are there any Use Cases where this may be beneficial?

You probably can figure it out for yourself: try as hard as you can('t), I defy you to find one ;)

Upvotes: 5

Related Questions