Reputation: 39
I'm an experienced C developer, and I'm wanting to know the equivalent to a header file in Java. I have an enum that I would like to be shared between two classes, but without header files, I'm not sure how to do this.
Is the standard way to have a super class, with a definition inside of it, then have the other two classes inherit from that? Google mentioned interfaces, but I don't have any experience with that.
Upvotes: 0
Views: 4220
Reputation: 149075
Jave does not use headers, but directly imports declarations from other classes. In C++ (or C) you commonly split the declarations that go into headers from the definitions that go in source files, and start the files with a bunch of #include
to load the external declarations.
In Java, you start the files by an equivalent bunch of import
statements to declare the external classes or static symbols you need to use in on source.
To answer the exact question, you can either make the enum a plain class, or make it an inner (static) class of one of the to classes and access it from the other - provided access rights allow it.
You must know that Java has no notion of friendyness. The closer that exist is the default access of package private that declares the symbol to be accessible by all classes from same package. You can use that if you do not want the enum to be publicly accessible.
Upvotes: 0
Reputation: 35457
A concrete example:
mypackage/MyEnum.java
(define the enum)
package mypackage;
public enum MyEnum {
VALUE_1, VALUE_2;
}
mypackage/MyClass.java
(use the enum)
package mypackage;
public class MyClass {
public void doSomething(MyEnum myEnum) {
switch(myEnum) {
case VALUE_1:
// do something
break;
case VALUE_2:
// do something
break;
}
}
}
otherpackage/OtherClass.java
(use the enum in another package)
package otherpackage;
import mypackage.MyEnum; // explicitly import as MyEnum is not in the same package as this class.
public class OtherClass {
public MyEnum provideEnum() {
return MyEnum.VALUE_1;
}
}
Upvotes: 0
Reputation: 5067
It depends on what level of encapsulation you want to accomplish. If you want to have the enum available just in the two classes that you mentioned then you could define it in the following ways:
I would prefer the first approach, it my opinion it is cleanest and it also follows the OOP best practices.
As for interfaces, they used to be used before enums to provide a "container" for constants, but in my opinion currently they shouldn't be used for this case.
Upvotes: 0
Reputation: 527
You should understand packages in Java.
Basics: https://en.wikipedia.org/wiki/Java_package
Access level modifiers: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If you have an enum which is not private, it can be accessed from that package.
Upvotes: 1