Java Interface conventions with getters and setters - java

I'm working on an application in which I have two fairly similar object classes whose fields need to be normalized. Many of the fields that need to be normalized are shared by both of these classes, but there are some that pertain only to one or the other.
I was thinking to create an interface with getters and setters for all of the fields that need to be normalized, that way I could pass both objects to the same class and access the fields / set the normalized values via the interface methods. Would this be considered bad convention?
Below is simplified example-- the objects I am normalizing will only ever be read from once the normalization is completed. Thanks in advance!
class A implements C{
T x;
T y;
T z;
...
}
class B implements C{
T x;
T y;
T k; // no 'z', above has no k
....
}
interface C {
public T getX();
public void setX(T x);
public T getY();
public void setY(T y);
public T getZ();
public void setZ(T z);
public T getK();
public void setK(T k);
}

If the code is properly documented saying A does not support
public T getK();
public void setK(T k);
and B does not support
public T getZ();
public void setZ(T z);
then I think you can go ahead with this design.
And, also construct UnsupportedOperationException with the specified detail message for the classes that doesn't support some of the methods of C. For example,
class A implements C{
T x;
T y;
T z;
...
public T getK(){
throw new UnsupportedOperationException("YOUR MESSAGE");
}
}

Isn't implementing an interface and providing an empty implementation a bad design issue? though you document it, it goes against the concept of interface and is inconsistent as you may have an empty implementation of one method in one class, and another implementation in another class and the code will become inconsistent in the long run, making it unsafe.. consider this
interface iSample {
void doThing1();
void doThing2();
void doThing3();
}
class sClass1 implements iSample {
void doThing1() { //doThing1 code }
void doThing2() { //doThing2 code }
void doThing3() { } // empty implementation
}
class sClass2 implements iSample {
void doThing1() { //doThing1 code }
void doThing2() { } // empty implementation
void doThing3() { //doThing2 code }
}
class Test {
public static void main (String[] args) {
testing(new sClass1());
testing(new sClass2());
}
public void testing(iSample s) {
// you would have no idea here which object has omitted which method.
s.doThing1();
s.doThing2();
s.doThing3();
}
as stated above you would have no idea which object has omitted which method and inconsistency prevails.

Well, based on your description, you would have empty methods inside both of your classes because you won't need them. class A would leave getK and setK unimplemented, and class B would do the same with getZ and setZ.
In this case it might be best to use a parent class that has x and y, and leave the implementation of z and k local to class A and class B, respectively.

Highly similar classes?
This sounds like a really good time to design for inheritance. Note that designing for inheritance should be a really deliberate decision ... because there's a right way to do it which will make your API a joy to use and a wrong way which can make your API a hassle to use.
You can also use an interface-based type system as you are suggesting. This has the advantage of being applicable to classes that may not otherwise be related.
Or you can do both.
I suggest that you capture the essence of the relationship in your classes and describe that as the contract for your interface-based type system.
Then, I suggest that you produce a skeletal implementation of your contract in an abstract skeletal implementation class. Your concrete classes can inherit from your skeletal implementation and, if done well, will inherit much of the behavior and state that describes the essence of your contract.
Note that you should use your interface as the type designation for all your objects, much like we do with the Java Collections API. It is not encouraged to declare a parameter type as void myFunc(HashMap m); the best practice is to declare void myFunc(Map m). In the latter case, Map represents the interface-based type system for all the different implementors of the Map contract.

Related

Associate interfaces with classes without source access

Here's the problem, I have two drawing JAR libraries (A and B). Both provide separate but useful functionality. However, in their infinite wisdom they have two different concepts of the basic point class.
Neither has any interesting or particularly unique methods or fields and both basically boil down to:
public class PointA{
double x;
double y;
}
and
public class PointB{
double x;
double y;
}
The functions in these libraries have methods that look like:
public static List<PointA> doInterestingThing();
or
public static PointB calculateThatThing();
I feel like there should be some nice way to just understand that these two classes are for all intents, the same.
If I had source access I could just have them implement some IPoint interface, but both libraries are in JARS.
The way I see it, there are several options:
Convert one to the other. Either make functions to convert all PointA's to PointB's or vice versa. That would mean essentially making a abstraction layer atop one of the libraries by wrapping every function in it with some boilerplate conversion code.
public static List<PointA>doInterestingThingWrapper(){
return convertPoints(LibraryB.doInterestingThing());
}
Make some third class PointC, that both library's results are converted to which represented my code's understanding of a point. Same problems as above, but now I need to write two times as many boilerplate conversions!
Edit the JARS directly. Obviously this is not preferable. However, it would allow me make PointA and PointB implement the same interface.
Some magic dynamic interface interaction I don't know about.
Could it be that Java has some way of dynamically assigning interfaces to already loaded classes?
Something like:
public interface IPoint{
double getX();
double getY();
}
public static void main(){
//Magical made up linking syntax
PointA implements IPoint{
public getX(){
this.getX()//PointA's method
}
public getY(){
this.getY(){//pointA's method
}
}
//And same for pointB
//And now we can say things like:
List<? extends IPoint> listOPoints=A.doInterestingThing();
//and:
IPoint thePoint=B.calculateThatThing();
}
I apologize in advance if this is a duplicate. I didn't even know what to call the problem which makes searching hard. If there's some obvious design pattern (adapter pattern?) that I missed that solves this, let me know.
You have two solutions
Use reflection and unreflection to use same named functionatily.
Wrap both in your project code into a object that implements the interface.
Sample:
class A { public void d(){}}
class B { public void d(){}}
interface D { void d(); }
class AD extends A implements D {}
class BD extends B implements D {}
Or
class AD implements D {A obj = new A(); public void d(){obj.d();}}

Is it bad practice to use Consumers as setters and Suppliers as getters in Java?

I have a Java class that has some private variable that I don't intend to create setters and getters for; I want these variables to remain inaccessible. But there is one class that needs access to these variables. This class is a visitor in a different package (and I'd prefer to keep it in a different package). Is it bad practice to allow this class to provide the visitor with Consumers and Suppliers, that act as setters and getters, so that the visitor could read and modify these variables? If yes, please state the reasons.
Example:
A.java
public class A {
private int x;
private Consumer<Integer> setter;
private Supplier<Integer> getter;
public A(int v) {
x = v;
setter = new Consumer<Integer>() {
#Override
public void accept(Integer t) {
x = t;
}
};
getter = new Supplier<Integer>() {
#Override
public Integer get() {
return x;
}
};
}
public void accept(SomeVisitor visitor) {
visitor.setSetter(setter);
visitor.setGetter(getter);
visitor.visit(this);
}
}
SomeVisitor.java
public class SomeVisitor extends ParentVisitor {
private Consumer<Integer> setter;
private Supplier<Integer> getter;
public SomeVisitor() {
setter = null;
getter = null;
}
public void setSetter(Consumer<Integer> setter) {
this.setter = setter;
}
public void setGetter(Supplier<Integer> getter) {
this.getter = getter;
}
#Override
public void visit(A a) {
// Code that will, possibly, read and modify A.x
...
}
}
This way the variable A.x remains inaccessible to every class except the visitor.
More Details:
I have some classes that will make use of the visitors. These classes have private variables that are dependent on one another. If these variables had setters, inconsistencies could arise as users change these variables, that should be dependent on one another, without respecting these dependecies.
Some of these variables will have getters, others won't as they will only be used internally and shouldn't be accessed elsewhere. The reason the visitors are an exception and should get read/write access to these variables is that the functionality the visitors are intended to implement were meant to be implemented within methods in these classes. But I thought it will be cleaner if I used visitors. And these functionalities do need read/write access to these variables.
The intention behind this approach was to emulate the friend feature in C++. I could place the visitors within the same package as these classes (which I would do if I didn't find a neat solution to this problem); But I think the package will look messy if it had the visitors as well (and there will be many visitors).
The functionality the visitors will implement will also have something to do with these classes relations to one another.
I tried to squeeze it into a comment, as it technically does not answer the question about whether this is a "Bad Practice™", but this term is hard to define, and thus, it is nearly impossible to give an answer anyhow...
This eventually seems to boil down to the question of how to Make java methods visible to only specific classes (and there are similar questions). The getter/setter should only be available to one particular class - namely, to the visitor.
You used very generic names and descriptions in the question, and it's hard to say whether this makes sense in general.
But some points to consider:
One could argue that this defeats the encapsulation in general. Everybody could write such a visitor and obtain access to the get/set methods. And even though this would be a ridiculous hack: If people want to achieve a goal, they will do things like that! (sketeched in Appendix 1 below)
More generally, one could argue: Why is only the visitor allowed to access the setter/getter, and other classes are not?
One convincing reason to hide getter/setter methods behind Supplier/Consumer instances could be related to visibility and the specificness of classes (elaborated in Appendix 2). But since the visitor always has the dependency to the visited class, this is not directly applicable here.
One could argue that the approach is more error prone. Imagine the case that either the setter or the getter are null, or that they belong to different instances. Debugging this could be awfully hard.
As seen in the comments and other answer: One could argue that the proposed approach only complicates things, and "hides" the fact that these are actually setter/getter methods. I wouldn't go so far to say that having setter/getter methods in general already is a problem. But your approach is now to have setter-setters and getter-setters in a visitor. This extends the state space of the visitor in a way that is hard to wrap the head around.
To summarize:
Despite the arguments mentioned above, I would not call it a "bad practice" - also because it is not a common practice at all, but a very specific solution approach. There may be reasons and arguments to do this, but as long as you don't provide more details, it's hard to say whether this is true in your particular case, or whether there are more elegant solutions.
Update
For the added details: You said that
inconsistencies could arise as users change these variables
It is usually the responsibility of a class to manage its own state space in a way that makes sure that it is always "consistent". And, in some sense, this is the main purpose of having classes and encapsulation in the first place. One of the reasons of why getters+setters are sometimes considered as "evil" is not only the mutability (that should usually be minimized). But also because people tend to expose properties of a class with getters+setters, without thinking about a proper abstraction.
So specifically: If you have two variables x and y that depend on one another, then the class should simply not have methods
public void setX(int x) { ... }
public void setY(int y) { ... }
Instead, there should (at best, and roughly) be one method like
public void setState(int x, int y) {
if (inconsistent(x,y)) throw new IllegalArgumentException("...");
...
}
that makes sure that the state is always consistent.
I don't think that there is a way of cleanly emulating a C++ friend function. The Consumer/Supplier approach that you suggested may be reasonable as a workaround. Some (not all) of the problems that it may cause could be avoided with a slightly different approach:
The package org.example contains your main class
class A {
private int v;
private int w;
public void accept(SomeVisitor visitor) {
// See below...
}
}
And the package org.example also contains an interface. This interface exposes the internal state of A with getter+setter methods:
public interface InnerA {
void setV(int v);
int getV();
void setW(int w);
int getW();
}
But note that the main class does not implement this interface!
Now, the visitors could reside in a different packakge, like org.example.visitors. And the visitor could have a dedicated method for visiting the InnerA object:
public class SomeVisitor extends ParentVisitor {
#Override
public void visit(A a) {
...
}
#Override
public void visit(InnerA a) {
// Code that will, possibly, read and modify A.x
...
}
The implementation of the accept method in A could then do the following:
public void accept(SomeVisitor visitor) {
visitor.accept(this);
visitor.accept(new InnerA() {
#Override
public void setX(int theX) {
x = theX;
}
#Override
public int getX() {
return x;
}
// Same for y....
});
}
So the class would dedicatedly pass a newly created InnerA instance to the visitor. This InnerA would only exist for the time of visiting, and would only be used for modifying the specific instance that created it.
An in-between solution could be to not define this interface, but introduce methods like
#Override
public void visit(Consumer<Integer> setter, Supplier<Integer> getter) {
...
}
or
#Override
public void visit(A a, Consumer<Integer> setter, Supplier<Integer> getter) {
...
}
One would have to analyze this further depending on the real application case.
But again: None of these approaches will circumvent the general problem that when you provide access to someone outside of your package, then you will provide access to everyone outside of your package....
Appendix 1: A class that is an A, but with public getter/setter methods. Goodbye, encapsulation:
class AccessibleA extends A {
private Consumer<Integer> setter;
...
AccessibleA() {
EvilVisitor e = new EvilVisitor();
e.accept(this);
}
void setSetter(Consumer<Integer> setter) { this.setter = setter; }
...
// Here's our public setter now:
void setValue(int i) { setter.accept(i); }
}
class EvilVisitor {
private AccessibleA accessibleA;
...
public void setSetter(Consumer<Integer> setter) {
accessibleA.setSetter(setter);
}
...
}
Appendix 2:
Imagine you had a class like this
class Manipulator {
private A a;
Manipulator(A a) {
this.a = a;
}
void manipulate() {
int value = a.getValue();
a.setValue(value + 42);
}
}
And now imagine that you wanted to remove the compile-time dependency of this class to the class A. Then you could change it to not accept an instance of A in the constructor, but a Supplier/Consumer pair instead. But for a visitor, this does not make sense.
As getters and setters are evil anyway, you'll be better off making things not more complicated than ordinary getters and setters.

Java inheritance: multiple extends needed

I design my game application and face some troubles in OOP design.
I want to know some patterns which can help me, because java have not any multiple extends option. I will describe my problem below, and also explain why multiple interface doesn't help me at all. Lets go.
What we want is "class is set of features". By feature I mean construction like:
field a;
field b;
field c;
method m1(){
// use, and change fields a,b,c;
}
method m2(){
// use, and change fields a,b,c;
}
//etc
So, basically the feature is a set of methods and corresponding fields. So, it's very close to the java interface.
When I talk that class implemets "feature1" I mean that this class contains ALL "feature needed" fields, and have realisation of all feature related methods.
When class implements two features the tricky part begins. There is a change, that two different features contains similar fields (names of this fields are equal). Let the case of different types for such fields will be out of scope. What I want - is "feature naming tolerance" - so that if methodA() from feature A change the field "common_field", the methodB from feature B, that also use "common_field" as field will see this changes.
So, I want to create a set of features (basically interfaces) and their implementations. After this I want to create classes which will extends multiple features, without any copy-paste and other crap.
But I can't write this code in Java:
public static interface Feature1 {
public void method1();
}
public static interface Feature2 {
public void method2();
}
public static class Feature1Impl implements Feature1 {
int feature1Field;
int commonField;
#Override
public void method1() {
feature1Field += commonField;
commonField++;
}
}
public static class Feature2Impl implements Feature2 {
int feature2Field;
int commonField;
#Override
public void method2() {
commonField++;
}
}
public static class MyFeaturedClass extends Feature1Impl, Feature2Impl implements Feature1, Features2 {
}
So, as you can see the problem are really complex.
Below I'll describe why some standart approaches doesn't work here.
1) Use something like this:
public static class MyFeaturesClass implements Feature1,Feature2{
Feature1 feature1;
Feature2 feature2;
#Override
public void method2() {
feature2.method2();
}
#Override
public void method1() {
feature1.method1();
}
}
Ok, this is really nice approach - but it does not provide "feature field name tolerance" - so the call of method2 will not change the field "commonField" in object corresponding the feature1.
2) Use another design. For what sake you need such approach?
Ok. In my game there is a "unit" concept. A unit is MOVABLE and ALIVE object.
Movable objects has position, and move() method. Alive objects has hp and takeDamage() and die() methods.
There is only MOVABLE objects in my game, but this objects isn't alive.
Also, there is ALIVE objects in my game, but this objects isn't movable (buildings for example).
And when I realize the movable and alive as classes, that implements interfaces, I really don't know from what I should extends my Unit class. In both cases I will use copy-paste for this.
The example above is really simple, actually I need a lot of different features for different game mechanics. And I will have a lot of different objects with different properties.
What I actually tried is:
Map<Field,Object> fields;
So any object in my game has such Map, and to any object can be applied any method. The realization of method is just take needed fields from this map, do its job and change some of them. The problem of this approach is performance. First of all - I don't want to use Double and Interger classes for double and int fields, and second - I want to have a direct accsess to the fields of my objects (not through the map object).
Any suggestions?
PS. What I want as a result:
class A implements Feature1, Feature2, Feature3, Feature4, Feature5 {
// all features has corresponding FeatureNImpl implementations;
// features 1-2-3 has "shared" fields, feature 3-4 has, features 5-1 has.
// really fast implementation with "shared field tolerance" needed.
}
One possibility is to add another layer of interfaces. XXXProviderInterface could be defined for all possible common fields, that define a getter and setter for them.
A feature implementation class would require the needed providers in the constructor. All access to common fields are done through these references.
A concrete game object class implementation would implement the needed provider interfaces and feature interfaces. Through aggregation, it would add the feature implementations (with passing this as provider), and delegate the feature calls to them.
E.g.
public interface Feature1 {
void methodF1();
}
public interface Feature2 {
void methodF2();
}
public interface FieldAProvider {
int getA();
void setA(int a);
}
public class Feature1Impl implements Feature1 {
private FieldAProvider _a;
Feature1Impl(FieldAProvider a) {
_a = a;
}
void methodF1() {
_a.setA(_a.getA() * 2);
}
}
// Similar for Feature2Impl
public class GameObject implements Feature1, Feature2, FieldAProvider
{
int _fieldA;
Feature1 _f1;
Feature2 _f2;
GameObject() {
_f1 = new Feature1Impl(this);
_f2 = new Feature2Impl(this);
}
int getA() {
return _fieldA;
}
void setA(int a) {
_fieldA = a;
}
void methodF1() {
_f1.methodF1();
}
void methodF2() {
_f2.methodF2();
}
}
However, I don't think this is an optimal solution

Valid use of polymorphism?

I have 2 classes that perform a very similar task, but require different data types passed to them in order to perform those functions.
They both ultimately write to files and have expose a single public method: write() using the constructor for simple dependency injection.
This is where they differ - 1 class accepts a single object of a specific type, while the other accepts an array of that object type.
Is this a valid case for polymorphism? I think it can be but tehcnically should not?
How is this situation to be correctly handled i.e. 2 or more classes which perform a very similar function, but in a slightly different way and crucially, require different data types passed in as dependencies?
You need overloaded methods in this case. One which works with single object and other with a number of objects. They should be in the same class.
Here is an easy-to-remember way of when to use what:
1. Overloading is when you need to do the same thing with different data
2. Overriding is when you need to do the same thing with the same data in a different way
public class FileWriter {
public void write(File from){ // single file
// magic logic
}
public void write(File... from){ // multiple files using varargs
// magic logic
}
}
If you only have two Write methods, one taking a single object and the other taking a List of objects -> I would put both methods on the same class.
If you have one Write for each type, I would go for generics.
Introducing a base class wouldn't be my first choice, better to extract the general stuff into another class and use it from different classes (has-a instead of is-a).
Polymorphism is only useful if you have the same method signature but need to do stuff in different ways.
Hard to answer without a particular code sample, but the scenario you've presented fits something similar to a decorator pattern:
class X
{
public void doSomething(int number) { ... }
};
class XForCollections
{
public XForCollections(X x) { ... }
public void doSomething(int[] numbers) { ... }
};
Note, that it's not really a decorator, as XForCollection doesn't inherit X.
Use an abstract generic superclass with the common stuff.
If you want WriterA that writes an argument of type ArgA, and WriterB that writes an argument of type ArgB, you'll make
an abstract Writer<T> with all of the common stuff in it, and an abstract method such as public void write(T arg)
WriterA that extends Writer<ArgA>
WriterB that extends Writer<ArgB>
Say you have this:
class A{
void write(int a){}
}
class B{
void write(int[] a){}
}
Since you say the implementations for those methods vary deeply between each other, then varargs probably wouldn't be a suitable option. To simplify things, do this::
class WriteStuff{
void write(int a){}
void write(int[] a){}
}
This would let you attain a higher level of cohesion for your classes. Polymorphism isn't really necessary here.
Then again, it's really too little information to go on with. You should probably write up some example code.
Polymorphism – means the ability of a single variable of a given type to be used to reference objects of
different types, and automatically call the method that is specific to the type of object the variable references. In a
nutshell, polymorphism is a bottom-up method call. The benefit of polymorphism is that it is very easy to add new
classes of derived objects without breaking the calling code that uses the polymorphic classes or interfaces. When you send a message to an object even though you
don’t know what specific type it is, and the right thing happens, that’s called polymorphism. The process used by
object-oriented programming languages to implement polymorphism is called dynamic binding.
Example:
Launcher
private void init() {
//client or calling code
double dim = 5.0; //i.e. 5 meters radius or width
List<Shape> listShapes = new ArrayList<Shape>(20);
Shape s = new Circle();
listShapes.add(s); //add circle
s = new Square();
listShapes.add(s); //add square
getTotArea (listShapes,dim); //returns 78.5+25.0=103.5
//Later on, if you decide to add a half circle then define
//a HalfCircle class, which extends Circle and then provide an
//area(). method but your called method getTotArea(...) remains
//same.
}
/** called method: method which adds up areas of various
** shapes supplied to it.
**/
public double getTotArea(List<Shape> listShapes, double dim){
Iterator<Shape> it = listShapes.iterator();
double totalArea = 0.0;
//loop through different shapes
while(it.hasNext()) {
Shape s = (Shape) it.next();
totalArea += s.area(dim); //polymorphic method call
}
return totalArea ;
}
}
Shape
public abstract class Shape {
protected abstract double area(double dim);
}
Square
public class Square extends Shape{
#Override
protected double area(double dim) {
return dim*dim;
}
}
Circle
public class Circle extends Shape{
#Override
protected double area(double dim) {
return Math.PI*dim*dim;
}
}

Inner class within Interface

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.

Categories