How to properly access static member classes?

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

This means that 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 the warning "Static field Foo.bar shoudl can be obtained in a static way." Can someone explain why this is so and offers the "right" implementation.

I understand that I can access static instances directly, but if you have a long hierarchy of packages, this becomes ugly:

 assertEquals(net.FooCorp.divisions.A.package.Foo.bar, 1); assertEquals(net.FooCorp.divisions.B.package.Foo.bar, 2); 
+4
source share
5 answers

I agree with others that you probably think about it wrongly. From this point of view, this may work for you if you only get access to static members:

 public class A { public static class Foo extends package1.Foo {} } public class B { public static class Foo extends package2.Foo {} } 
+1
source

You should use:

 Foo.bar 

And not:

 A.foo.bar 

What a warning means.

The reason is that bar not a member of the Foo instance. Rather, bar is global, for the Foo class. The compiler wants you to reference it globally, rather than pretending to be a member of this instance.

+11
source

It makes no sense to put these two static variables in classes if you only need to access the static members. The compiler expects you to access them through a class name prefix, for example:

 package1.Foo.bar package2.Foo.bar 
+2
source

Once you have created the object in:

 public static package1.Foo foo; 

it is not accessible on a static path. You will need to use the class name and, of course, the full package name for the class address, since they have the same name in different packages

+2
source

It is true that an instance of Foo has access to the static fields of Foo, but think about the word "static". This means โ€œstatically linkedโ€, at least in this case. Since A.foo is of type Foo, "A.foo.bar" will not query the object for "bar", it will go directly to the class. This means that even if the subclass has a static field called "bar" and foo is an instance of this subclass, it is going to get Foo.bar, not FooSubclass.bar. Therefore, it is better to refer to it with the name of the class, because if you try to use inheritance, you will shoot in the leg.

0
source

Source: https://habr.com/ru/post/1276820/


All Articles