public interface AFEvent {
public String UNKNOWN ="Unknown";
public String ERROR = "EQUINOX_EVENT_ERROR";
public String REJECT = "EQUINOX_EVENT_REJECT";
public String ABORT = "EQUINOX_EVENT_ABORT";
}
And
public class AFEvent {
public static final String UNKNOWN ="Unknown";
public static final String ERROR = "EQUINOX_EVENT_ERROR";
public static final String REJECT = "EQUINOX_EVENT_REJECT";
public static final String ABORT = "EQUINOX_EVENT_ABORT";
}
Then I can call it in the same way.
Whats the difference when calling attribute from interface vs static class ?
fields declared in interface are by default static and final. So, no difference if they are to be used as final constants.
On using final properties, there is no difference. The main difference between interfaces and classes is that on interfaces you can not provide a method implementation but only contracts, in order to force any class implementing your interface to provide implementations for those method contracts. On classes, you can provide method implementations (and contracts, if declared abstract).
Related
I have an abstract class that has some constants that each child class will use. Each one of them is static, final and immutable.
public abstract class MyAbstract {
//some private instance fields
protected static final long LONG_ID = 1;
protected static final String STRING_ID = "example_id";
//some methods
}
I know that having protected static final is bad practice but what about protected static finals that are immutable?
I know that I can make them public but I'd like to avoid doing so as the constants refer to specific ID's that user doesn't need to know.
To answer your question in the title "What is the best practice of inheriting constants in Java?", my answer is: do not inherit them at all.
Inheritance has a special meaning and purpose in object oriented programming, and using inheritance just for convenience because you want to be able to access constants in a particular set of classes does not correspond to this meaning and purpose.
If you have constants that you want to be able to use in different classes, you can put the constants in a separate class. Make this class final and make the constructor private so that it can't be subclassed and instantiated:
package com.example;
public final class Constants {
public static final long LONG_ID = 1L;
public static final String STRING_ID = "example_id";
// Private constructor, this class should not be instantiated
private Constants() {
}
}
Then, in a class where you want to use the constants, use import static:
import static com.example.Constants.LONG_ID;
public class Example {
public void someMethod() {
// Use the constant
long id = LONG_ID;
System.out.println(id);
}
}
The advantage is that the class Example does not need to extend class Constants or implement an interface, so you do not need to misuse inheritance, while you still have the same convenience of being able to use the constants with concise syntax.
I want to define a class with a constructor that takes an enum as a formal argument (so only arguments which conform with the enum type can be passed). Here's what I have (generalised as I'm doing college work and don't want to plagiarise):
public class EnumThing
{
private SomeConstant aConstant;
private enum SomeConstant {CONSTANT1, CONSTANT2, CONSTANT3};
public EnumThing(SomeConstant thisConstant)
{
this.aConstant = thisConstant;
}
// Methods
However when I try
EnumThing doodah = new EnumThing(CONSTANT1);
I get an error: cannot find symbol - variable CONSTANT1
This is my first attempt to use enums for anything at all. They seem excitingly powerful but it seems like I'm using them wrong. Any help hugely appreciated!
First of all, you need to make the enum public otherwise you cannot access it outside of the class EnumThing:
public class EnumThing {
public enum SomeConstant {CONSTANT1, CONSTANT2, CONSTANT3}
// ...
}
Then, access the members of the enum correctly:
EnumThing doodah = new EnumThing(EnumThing.SomeConstant.CONSTANT1);
Full working example (note that the correct usage is: SomeConstant.CONSTANT1):
public class EnumThing {
private SomeConstant aConstant;
private enum SomeConstant {CONSTANT1, CONSTANT2, CONSTANT3}
public EnumThing(SomeConstant thisConstant) {
this.aConstant = thisConstant;
}
public static void main(String[] args) {
EnumThing doodah = new EnumThing(SomeConstant.CONSTANT1);
}
}
Note that you can use a private enum. But it will only be accessible within your class (EnumThing).
So a while back I created a SQLiteHelper Class in my Android App. I'm not 100% certain why, but the table and column names were public static final fields in a nested public static abstract class. As I recall, the goal was to protect the fields from being modified. It all works great but things are starting to get sophisticated with my app and I want to populate fields in other classes with the public static final table and column name fields. After some trial and error, and reading about abstract classes, static classes, and nesting classes, it occurred to me that can just call the field directly, as in.
String myTable = MySQLiteHelper.dbFields.TABLE_NAME_REMINDER;
Even though I've read up on these topics, how it all comes together in my specific case is still making me scratch my head. So my question is, since the fields are static final, does nesting the fields actually provide additional protection, and if the nested class is static, why also make it abstract? Is static AND abstract required to call it directly without needing to instantiate the outer and nested classes?
Thanks for the help. I'm really trying to get my head wrapped around the various class implementations.
Here's the key elements of the class :
public class MySQLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Reminders.db";
private static final int DATABASE_VERSION = 5;
public int DatabaseVersion = DATABASE_VERSION;
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static abstract class dbFields implements BaseColumns {
//dbFields Table Fields
public static final String TABLE_NAME_REMINDER = "reminders";
public static final String COLUMN_REMINDER_ID = _ID;
public static final String COLUMN_REMINDER = "reminder";
public static final String COLUMN_REMINDER_ALTITUDE = "altitude";
public static final String COLUMN_REMINDER_USED = "is_used";
public static final String COLUMN_REMINDER_LASTUSED = "last_used";
public static final String COLUMN_REMINDER_ACTION = "action";
public static final String COLUMN_REMINDER_SCORE = "score";
public static final String COLUMN_REMINDER_RELATIONSHIP = "relationship";
//Special_Days Table Fields
public static final String TABLE_NAME_SPECIAL_DAYS = "special_days";
public static final String COLUMN_SPECIAL_DAYS_ID = _ID;
public static final String COLUMN_SPECIAL_DAYS_DATE = "date"; //dbDataRow strField 1
public static final String COLUMN_SPECIAL_DAYS_NAME = "name"; //dbDataRow dbData
public static final String COLUMN_SPECIAL_DAYS_ALTITUDE = "altitude"; //dbDataRow intField 1
public static final String COLUMN_SPECIAL_DAYS_USED = "is_used"; //dbDataRow Field 2
public static final String COLUMN_SPECIAL_DAYS_WARNING = "warning"; //dbDataRow intField 3
public static final String COLUMN_SPECIAL_DAYS_ACTION = "action"; //dbDataRow intField 4
}
}
since the fields are static final, does nesting the fields actually provide additional protection
No, it doesn't. As you've seen, you can access the fields even if they're nested and, since they're static and final, you can't modify them.
and if the nested class is static, why also make it abstract? Is static AND abstract required to call it directly without needing to instantiate the outer and nested classes?
The purpose of abstract is to allow you to have a base class that has a method with no implementation. One classic example is an Animal class. All animals make a noise (probably not, but let's pretend) so the Animal class should have a makeNoise method. But, every animals noise is different so it doesn't make sense to have any implementation in the base class. The Cat subclass might look like public String makeNoise() { return "meow"; } and the Dog subclass might return "woof", but there's no sane implementation of makeNoise on the base class. However, if you didn't have any makeNoise on the base class you couldn't ask an arbitrary animal to makeNoise. So you'd have a public abstract String makeNoise() method on the base. That lets you call makeNoise for any animal even if all you have is a reference to an Animal.
Note that abstract has nothing to do with the class being nested or not. Other classes, nested or not, can inherit from a nested static class. It also has nothing to do with hiding data or otherwise protecting data or code.
So, to answer your question: you should make it abstract if and only if the purpose of being abstract applies here. Given your sample code, it doesn't.
since the fields are static final, does nesting the fields actually provide additional protection
Not if the nested class is public: it just provides a notational inconvenience.
and if the nested class is static, why also make it abstract?
No idea, it's your class.
Is static AND abstract required to call it directly without needing to instantiate the outer and nested classes?
No, static is sufficient.
I don't see any need for the BaseColumns interface here either. I would look seriously at using an Enum for the column names.
I have this class declaration
abstract class A {
protected static String message = "Hello";
}
And I want this field to get propagated to subclasses, to avoid typing protected static String message = "Whatever"; (the value of this static field is different in each subclass) in all the subclasses.
I know this won't work:
class B extends A {
static {
message = "Blablabla";
}
}
Because it will actually modify A's message because static fields/methods are not inherited. What I want to know is if there's any other way of doing this, or if I have to rewrite the static field on each subclass.
I would suggest using a protected method getMessage() that gets overridden by each subclass instead of a static field.
class B extends A {
#Override
protected String getMessage() {
return "Blablabla";
}
}
There's no straightforward way to do it.
You may consider use some utility class which maps a Class object to a message. This will help you use general methods to work with messages based on this.getClass().
I usually create a get method in this case:
abstract class A {
private static final String DEFAULT_MESSAGE = "Hello";
protected String getMessage() {
return DEFAULT_MESSAGE;
}
}
That makes it easy to override the message in subclasses where I want to.
Static fields and methods are inherited - as a C programmer, I was told to think of them as being similar to "global" variables, namespaced to the class (and with private/protected restrictions).
From your first snippet, B.message will be "Hello".
You have to make it either
public class A {
protected String message = "Hello";
}
or
public class A {
private static String message = "Hello";
}
public class B {
private static String message = "Howdy";
}
Would an aspect let you achieve what you want to do? From one place you could configure/manage the return value for a method with a specific nam, on a class-by- class basis. ...it would still be more work than duplicating the same boiler plate "private static ..." in each subclass.
Is it possible to create an inner class within an interface?
If it is possible why would we want to create an inner class like that since
we are not going to create any interface objects?
Do these inner classes help in any development process?
Yes, we can have classes inside interfaces. One example of usage could be
public interface Input
{
public static class KeyEvent {
public static final int KEY_DOWN = 0;
public static final int KEY_UP = 1;
public int type;
public int keyCode;
public char keyChar;
}
public static class TouchEvent {
public static final int TOUCH_DOWN = 0;
public static final int TOUCH_UP = 1;
public static final int TOUCH_DRAGGED = 2;
public int type;
public int x, y;
public int pointer;
}
public boolean isKeyPressed(int keyCode);
public boolean isTouchDown(int pointer);
public int getTouchX(int pointer);
public int getTouchY(int pointer);
public float getAccelX();
public float getAccelY();
public float getAccelZ();
public List<KeyEvent> getKeyEvents();
public List<TouchEvent> getTouchEvents();
}
Here the code has two nested classes which are for encapsulating information about event objects which are later used in method definitions like getKeyEvents(). Having them inside the Input interface improves cohesion.
Yes, you can create both a nested class or an inner class inside a Java interface (note that contrarily to popular belief there's no such thing as an "static inner class": this simply makes no sense, there's nothing "inner" and no "outter" class when a nested class is static, so it cannot be "static inner").
Anyway, the following compiles fine:
public interface A {
class B {
}
}
I've seen it used to put some kind of "contract checker" directly in the interface definition (well, in the class nested in the interface, that can have static methods, contrarily to the interface itself, which can't). Looking like this if I recall correctly.
public interface A {
static class B {
public static boolean verifyState( A a ) {
return (true if object implementing class A looks to be in a valid state)
}
}
}
Note that I'm not commenting on the usefulness of such a thing, I'm simply answering your question: it can be done and this is one kind of use I've seen made of it.
Now I won't comment on the usefulness of such a construct and from I've seen: I've seen it, but it's not a very common construct.
200KLOC codebase here where this happens exactly zero time (but then we've got a lot of other things that we consider bad practices that happen exactly zero time too that other people would find perfectly normal so...).
A valid use, IMHO, is defining objects that are received or returned by the enclosing interface methods. Tipically data holding structures. In that way, if the object is only used for that interface, you have things in a more cohesive way.
By example:
interface UserChecker {
Ticket validateUser(Credentials credentials);
class Credentials {
// user and password
}
class Ticket {
// some obscure implementation
}
}
But anyway... it's only a matter of taste.
Quote from the Java 7 spec:
Interfaces may contain member type declarations (§8.5).
A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.
It is NOT possible to declare non-static classes inside a Java interface, which makes sense to me.
An interesting use case is to provide sort of a default implementation to interface methods through an inner class as described here: https://stackoverflow.com/a/3442218/454667 (to overcome the problem of single-class-inheritance).
Yes it is possible to have static class definitions inside an interface, but maybe the most useful aspect of this feature is when using enum types (which are special kind of static classes). For example you can have something like this:
public interface User {
public enum Role {
ADMIN("administrator"),
EDITOR("editor"),
VANILLA("regular user");
private String description;
private Role(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
public String getName();
public void setName(String name);
public Role getRole();
public void setRole(Role role);
...
}
It certainly is possible, and one case where I've found it useful is when an interface has to throw custom exceptions. You the keep the exceptions with their associated interface, which I think is often neater than littering your source tree with heaps of trivial exception files.
interface MyInterface {
public static class MyInterfaceException extends Exception {
}
void doSomething() throws MyInterfaceException;
}
What #Bachi mentions is similar to traits in Scala and are actually implemented using a nested class inside an interface. This can be simulated in Java. See also java traits or mixins pattern?
Maybe when you want more complex constructions like some different implementation behaviours, consider:
public interface A {
public void foo();
public static class B implements A {
#Override
public void foo() {
System.out.println("B foo");
}
}
}
This is your interface and this will be the implementee:
public class C implements A {
#Override
public void foo() {
A.B b = new A.B();
b.foo();
}
public static void main(String[] strings) {
C c = new C();
c.foo();
}
}
May provide some static implementations, but won't that be confusing, I don't know.
I found a use fir this type of construct.
You can use this construct to defines and group all the static final constants.
Since, it is an interface you can implement this on an class.
You have access to all the constants grouped; name of the class acts as a namespace in this case.
You can also create "Helper" static classes for common functionality for the objects that implement this interface:
public interface A {
static class Helper {
public static void commonlyUsedMethod( A a ) {
...
}
}
}
I'm needing one right now. I have an interface where it would be convenient to return a unique class from several of it's methods. This class only makes sense
as a container for responses from methods of this interface.
Hence, it would be convenient to have a static nested class definition, which is associated only with this interface, since this interface should be the only place where this results container class is ever created.
For instance traits (smth like interface with implemented methods) in Groovy. They are compiled to an interface which contains inner class where all methods are implemented.