Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly access static member classes?

Tags:

java

static

I have two classes, and want to include a static instance of one class inside the other and access the static fields from the second class via the first.

This is so I can have non-identical instances with the same name.

Class A 
{
    public static package1.Foo foo;
}

Class B 
{
    public static package2.Foo foo;
}


//package1
Foo 
{
    public final static int bar = 1;
}

// package2
Foo
{
    public final static int bar = 2;
}

// usage
assertEquals(A.foo.bar, 1);
assertEquals(B.foo.bar, 2);

This works, but I get a warning "The static field Foo.bar shoudl be accessed in a static way". Can someone explain why this is and offer a "correct" implementation.

I realize I could access the static instances directly, but if you have a long package hierarchy, that gets ugly:

assertEquals(net.FooCorp.divisions.A.package.Foo.bar, 1);
assertEquals(net.FooCorp.divisions.B.package.Foo.bar, 2);
like image 344
fijiaaron Avatar asked Dec 08 '22 09:12

fijiaaron


1 Answers

You should use:

Foo.bar

And not:

A.foo.bar

That's what the warning means.

The reason is that bar isn't a member of an instance of Foo. Rather, bar is global, on the class Foo. The compiler wants you to reference it globally rather than pretending it's a member of the instance.

like image 169
Jason Cohen Avatar answered Dec 09 '22 22:12

Jason Cohen