I've got following Java classes defined:
mac-grek:javajunk grek$ cat A\$B.java
class A$B {}
mac-grek:javajunk grek$ cat A.java
public class A {
public static class B {}
}
mac-grek:javajunk grek$ cat Main.java
public class Main {
public static void main(String[] args) {
System.out.println(A.B.class.getName());
System.out.println(A$B.class.getName());
}
}
When I try to compile them, I get following errors:
mac-grek:javajunk grek$ javac 'A$B.java' A.java Main.java
A.java:2: duplicate class: A.B
public static class B {}
^
Main.java:4: cannot find symbol
symbol : class B
location: class A
System.out.println(A.B.class.getName());
^
Main.java:5: cannot find symbol
symbol : class A$B
location: class Main
System.out.println(A$B.class.getName());
^
3 errors
If I remove A.java
file and System.out.println(A.B.class.getName());
from Main.java
everything compiles:
mac-grek:javajunk grek$ cat A\$B.java
class A$B {}
mac-grek:javajunk grek$ cat Main.java
public class Main {
public static void main(String[] args) {
System.out.println(A$B.class.getName());
}
}
mac-grek:javajunk grek$ javac A\$B.java Main.java
mac-grek:javajunk grek$
So Java allows me to define a class containing dollar sign in it's name. How can I compile my original example?
Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed. Variable names should be short yet meaningful.
"Java does allow the dollar sign symbol $ to appear in an identifier, but these identifiers have a special meaning, so you should not use the $ symbol in your identifiers."
First, in Java '$' is a valid symbol for variable names and you can just use it for whatever you like: making your code cla$$ier, denoting that variables are private under a code convention, etc. Second, '$' is used as a separator character for the Java compiler to specify when a class is declared under another class.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.
You have a name conflict because you defined a top-level class A$B having the same name as the generated name for a static inner class B of class A. Since you have both, the compiler can't resolve the conflict.
The JLS says:
The $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.
Since you decided not to respect that rule, you got bitten by javac. I would just rename A$B to something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With