what is the use of writing a class inside an interface - java

I found the following example in one of the java forum.
interface employee{
class Role{
public String rollname;
public int roleId;
public Object person;
}
Role getRole();
// other methods
}
I have executed the above code snippet and it is compiling successfully.
Which means we can have a class inside an interface.
My question is what is the use of having such classes? Is it any design pattern?

This code snippet kind of answers your question already. The class Role is used by the employee interface in getRole() method. The designer of the interface decided that this class is so tightly coupled with the interface that it is worth to define it inside that interface to emphasize how important that class is for the interface.
Also it provides semantic namespace for the class: employee.Role. However I see this kind of construct for the first time while static classes defined inside other classes are quite common (for the same purposes as above).

The use here is the same as for any inner class. It limits the scope of the class to where it belongs.
In this case the implementer thought that Role was not fit as a top-level class, and put it inside the employee interface. The reason for this is most likely that the intention of Role is to be tightly coupled with employee.

The class provides an important part of the interface: A return value for getRole. So it makes sense to define the class within the interface.
It would be a bit more common to define an interface within an interface for this sort of thing (like Map.Entry in java.util), to allow more flexibility when implementing the interface, but you can do the class as well.

There is a slight compilation problem with your example, which I have fixed below:
public interface Employee {
class Role{
public String rollname;
public int roleId;
public Object person;
}
Role getRole();
}
Aside from that, yes, it compiles. That doesn't mean that doing this is a good idea. It's a further way of name-spacing your Role class, but I think it's rather ugly.

I wouldn't write such a piece of code, but I think the use is to emphasize the dependency between the class and the interface.
Interfaces are used to define API and in this case, the author may have wanted to say that "these two could not live apart".
Hope this helps.

I wouldn't write such a piece of code, but I think the use is to emphasize the dependency between the class and the interface.
Interfaces are used to define API and in this case, the author may have wanted to say that "these two could not live apart".

Related

A design confusion about inheritance and interfaces

I'm stuck with a rather peculiar design problem. I'm using a Java ORM, and have defined one of my model classes as follows:
class User extends Model {
// . . .
}
Now, there are more models, and I'd like them all to support data validations. The idea is simple: As each setter method is called, an internal ArrayList of errors keeps getting populated.
Now, the mechanism of error handling is exactly the same for all the model classes. I can envision the following interface:
public interface ErrorReportable {
ArrayList<String> errors = new ArrayList<String>();
boolean hasErrors();
ArrayList<String> getErrors();
void resetErrors();
}
Now I have a problem: All the methods are abstract, which means I'll have to provide an implementation for all of them in my classes. This is sad, because all these methods are going to be implemented in exactly the same way. Ideally, this would've been another class I would've neatly inherited from, but sadly, there's no multiple inheritance in Java.
My next option is use default methods in interfaces, but here the problem is the errors field, which will become static whereas I need a regular field for each instance.
It looks like the only solution is composition, but then I'll have to have a hasErrors() method on User, which will go return this.error_obj.hasErrors(). This is fine, but not really neat in my opinion as I'm having to write things twice.
How can I do better?
I think it would be better for the model classes to only expose List<Error> validate() method, and to have a stand-alone validator that validates all the fields and collects the errors.
That way, the collected messages are not part of the model's state, you have explicit control over when will the validation happen, you're preferring composition (which is almost always a good thing), and the only method you need to implement in model class is the entity-specific validation.
If you ever need to add any cross-field validations, it will also be probably quite easy to extend this design to also perform those alongside with field validations.
If I get your need right, I would implement an own Model-class, that implements all neceaasary Interfaces and extends the Model-ancestor, but still is Abstract.
Then all your normal model-classes inherit from your abstract model-class to get the implementation for the interface and also the inheritance from the model-class (2nd Generation would that be). Any framework checking with 'instance of' will still check true for the later model-class.
The abstract class does not even have to have any abstract methods/members, but it should stay abstract to prevent direct instanciating from that class.
public abstract class myModel extends Model implements ErrorReportable{ ... }
public class User extends myModel { ... }

Why should I use an interface when there is only one implementation class?

I'm new at programming and I'm learning Java.
I was just wondering why I should use an interface when there is only one implementation class?
You do this to prevent others from accessing your implementing type. For example, you could hide your implementing type inside a library, give the type package access, and return an instance of your interface to the users of your library:
// This is what the users of your library know about the class
// that does the work:
public interface SomeInterface {
void doSomethingUseful();
void doSomethingElse();
}
// This is the class itself, which is hidden from your clients
class MyImplementation implements SomeInterface {
private SomeDependency dependency = new SomeDependency();
public void doSomethingUseful() {
...
}
public void doSomethingElse() {
...
}
}
Your clients obtain objects like this:
public class MyFactory {
static SomeInterface make() {
// MyFactory can see MyImplementation
return new MyImplementation();
}
}
This trick becomes useful when the implementation uses lots of libraries. You efficiently decouple the interface of your library from its implementation, so that the user wouldn't have to know about the dependencies internal to your library.
One reason is to maintain the open/closed principle, which states that your code should be open for extension, but closed for modification. Although you only have one implementing class now, chance is that you will need another differing implementation class with the passing of time. If you extract the implementation into an interface beforehand, you just have to write another implementing class ie. You don't have to modify a perfectly working piece of code, eliminating the risks of introducing bugs.
You shoulnt do anything without thinking and reasoning.
There might be cases where you might want to add an interface even for a single implementation ... but IMO that's an OBSOLETE PRACTICE coming from old EJB times, that people use and enforce without the proper reasoning and reflection.
... and both Martin Fowler, Adan Bien, and others has been saying it for years.
https://martinfowler.com/bliki/InterfaceImplementationPair.html
https://www.adam-bien.com/roller/abien/entry/service_s_new_serviceimpl_why
To respect the Interface Segregation Principle.
The decision to create an interface should not be based on the number of implementing classes, but rather on the number of different ways that object is used. Each ways the object is used is represented by an interface, defined with the code that uses it. Say your object needs to be stored in memory, in collections that keep objects in order. That same object and also needs to be stored in some persistent storage.
Say you implement persistence first. What is needed by the storage system is a unique identifier for the persisted objects. You create an interface, say Storable, with a method getUniqueId. You then implement the storage.
Then, you implement the collection. You define what the collection needs from stored objects in an interface, like Comparable, with a method compareTo. You can then implement the collection with dependency on Comparable.
The class you want to define would implement both interfaces.
If the class you are defining implement a single interface, that interface would have to represent the needs of the collection and storage system. That would cause, for example:
unit tests for the collection would have to be written with objects that implement Storable, adding a level of complexity.
if the need arise later to display the object, you would have to add methods needed by the display code to the single interface, and modify the tests for collection and storage to also implement the methods needed for display.
I talk about impact on test code here. The problem is larger if other production level objects need storage and not display. The larger the project, the larger the issue created by not respecting the interface segregation principle will become.
It can give you the flexibility to add more implementations in the future without changing the client code which references the interface.
Another example of when it can be useful is to simulate multiple inheritance in Java when it is needed. For example, suppose you have an interface MyInterface and an implementation:
public interface MyInterface {
void aMethod1();
void aMethod2();
}
class MyInterfaceImpl implements MyInterface {
public void aMethod1() {...}
public void aMethod2() {...}
}
You also have an unrelated class with its own hierarchy:
public class SomeClass extends SomeOtherClass {
...
}
Now you want to make SomeClass be of type MyInterface but you also want to inherit all the code that is already existing in MyInterfaceImpl. Since you cannot extend both SomeOtherClass and MyInterfaceImpl, you can implement the interface and use delegation:
public class SomeClass extends SomeOtherClass implements MyInterface {
private MyInterface myInterface = new MyInterfaceImpl();
public void aMethod1() {
myInterface.aMethod1();
}
public void aMethod2() {
myInterface.aMethod2();
}
...
}
I see a lot of good points being made in this post. Also wanted to add my 2 cents to this collection of knowledge.
Interfaces Encourage parallel development in a team environment. There can be 2 classes A and B, with A calling B's API. There can be 2 developers simultaneously working on A and B. while B is not ready, A can totally go about it's own implementation by integrating with B's interfaces.
Interfaces serve as a good ground for establishing API Contracts between different layers of code.
It's good to have a separation of concerns with Interface handling implicit API documentation. it's super easy to refer to one and figure which APIs are accessible for the clients to call.
Lastly, it's better to practice using interfaces as a standard in a project than having to use it on a case by case bases (where you need multiple implementations). This ensures consistency in your project.
For the Art that Java Code is, interfaces make thmem even more beautiful :)
Interfaces can be implemented by multiple classes. There is no rule that only one class can implement these. Interfaces provide abstraction to the java.
http://www.tutorialspoint.com/java/java_interfaces.htm
You can get more information about interfaces from this link

Interface Class vs Class

I needed to do a java program for my class.
I did it and worked well.
In my code, I have some private methods. Do I need to build an Interface Class hide those private methods or they can be at the same class as the public methods?
At the moment all methods (public and private) are in the same class, but my coworker insists that I need to create an Interface to hide the private methods
No, you don't need to create an interface. An interface would hide them even more (from people's eyes, not from code) if you were to use the class only through the interface, but even without one, the private methods won't be available to other classes.
If you want to implement the "code to an interface" guideline fully, you can declare an interface for your public methods to implement.
What you can definitely not do is declare methods in an interface, then "implement" them as private in your class - that would reduce the visibility and not even compile.
Ultimately private methods are scoped to your class only.
It might help to repeat "what is the purpose of an Interface?"
It is: "a formal declaration of what, as far as anyone else should be concerned, this thing 'gives,' 'takes,' and 'does.'"
So ... if a client class wants to deal with "something that implements this Interface," and five other classes (none of which, say, are siblings or ancestors of one another ...), each in their own way, do so, then: any of the five would be compatible. Why? Because they supply all of the properties and/or methods that the interface requires. (That's what "implementing" actually means.)
None of this exposes any of the client's "private things." In fact, an Interface says absolutely nothing about how the class actually does what it has to do, nor what else it does. "Meet the requirements of the Interface, and you can get the job."

How do I group many interfaces into a common single interface? [duplicate]

This question already has answers here:
Why an interface can not implement another interface?
(7 answers)
Closed 9 years ago.
EDIT: The simple answer to my question is that Java allows one interface to extend multiple other interfaces. This is what answers my logical question of how you group interfaces together in a common interface. This answer did not appear in the dupe question. Also the question was different, it was not about creating interface groups.
Is there a reason in Java you cannot define one interface as implementing other interfaces? The answer I've seen and been dissatisfied with is that "interfaces themselves don't contain implementation, so how could an interface implement other other interfaces?" Well, that's a weak answer in my opinion, because its more a nod to English semantics than it is logical interpretation of the scenario. The logical interpretation of the scenario is since we can define classes to implement many interfaces, why can't we define an interface that itself represents a collection of interfaces.
Suppose you have many classes that you want to each implement a large, common set of many interfaces. As it currently stands, you'd have to explicitly write out the list for each class. This means that if later you had to add another interface to your list of many, you'd have to modify each class. Having all the interfaces consolidated in one "super interface" would allow the programmer to make the change in only one place.
And before you answer "make an abstract superclass that implements the list of interfaces, and have all your subclasses extend that superclass", keep in mind you cannot assume these classes do not already extend classes. One of the whole benefits of the implements keyword is so that you can adapt a class without having to change its taxonomy, right?
I guess the long story short is: Why can't programmers define interfaces that are just groups of other interfaces? Or, maybe the better question is: If I can't define an interface as implementing other interfaces, HOW can I define interfaces that are groups of other interfaces?
For those of you that prefer code, what I'm asking is why instead of doing this...
public class Foo extends ParentClass1 implements IBar1, IBar2, IBar3{
}
public class Baz extends ParentClass2 implements IBar1, IBar2, IBar3{
}
...wouldn't it make more sense for Java to allow this:
public interface IAllBar implements IBar1, IBar2, IBar3{
}
public class Foo extends ParentClass1 implements IAllBar{
}
public class Baz extends ParentClass2 implements IAllBar{
}
That way, later, if I create IBar4 I only have to modify IAllBar.java instead of Foo.java AND Baz.java.
Edit: So according to below answers I can define IAllBar to EXTEND all those interfaces and I'll get exactly what I want. I'm glad some people are willing to read an entire post before jumping to the bottom to post mean responses.
You can define an interface that's a collection of other interfaces. Its called extending an interface. You can extend multiple interfaces.
As for why you can't define methods in an interface, it's how Java interfaces were defined. And the problem you speak of are the consequences of single inheritance.
However you will be pleased to know that in the new upcoming Java 8 there's an feature called Virtual Extension Methods which addresses the large code base problems you speak of.
Personally I think it's useful in legacy code bases for quick refactoring, but if the system is well designed you should be able to get rid of the default implementations later. And overusing this feature will only result in all the disadvantages of multiple inheritance.
Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
I believe what you should do is extend interfaces.
You could do this as shown below:
public interface ManBearPig implements Man, Bear, Pig {
//interface body
}
You could then implement ManBearPig where you need it.
The thing you need to keep in mind is that interfaces support multiple inheritance.
To understand this consider the idea that interfaces Man, Bear, and Pig might each have the method walk() included within them.
If you were to implement ManBearPig in a class and call the walk() method it would implement the walk method of Man, Bear, and pig simultaneously.
According to my understanding, your problem statement is:
How to design a Type hierarchy where a group of Classes implement same set of Interfaces and a number of behaviors exposed by the interfaces have common implementation.
This kind of design problem can be solved in Java in the following way (explaining by your example code)
public abstract class AbstractAllBar implements IBar1, IBar2, IBar3{
/* Provide implementations of methods whose behavior remains unchanges for all of it's children classes.*/
}
Now this abstract class can be extended by the classes who have common set of behaviors as defined by the abstract class AbstractAllBar.
public class ParentClass1 extends AbstractAllBar {
.......
}
public class ParentClass2 extends AbstractAllBar {
.......
}
public class Foo extends ParentClass1 {
}
public class Baz extends ParentClass2 {
}
This kind of abstract classes provide Skeleton Implementation. Examples of Skeleton Implementation can be found in Collection API. You can refer source code of AbstractList and AbstractSet to make it more clear.

Is there anything bad in declaring nested class inside interface in java?

I have an interface ProductService with method findByCriteria. This method had a long list of nullable parameters, like productName, maxCost, minCost, producer and so on.
I refactored this method by introducing Parameter Object. I created class SearchCriteria and now method signature looks like this:
findByCriteria (SearchCriteria criteria)
I thought that instances of SearchCriteria are only created by method callers and are only used inside findByCriteria method, i.e.:
void processRequest() {
SearchCriteria criteria = new SearchCriteria ()
.withMaxCost (maxCost)
.......
.withProducer (producer);
List<Product> products = productService.findByCriteria (criteria);
....
}
and
List<Product> findByCriteria(SearchCriteria criteria) {
return doSmthAndReturnResult(criteria.getMaxCost(), criteria.getProducer());
}
So I did not want to create a separate public class for SearchCriteria and put it inside ProductServiceInterface:
public interface ProductService {
List<Product> findByCriteria (SearchCriteria criteria);
static class SearchCriteria {
...
}
}
Is there anything bad with this interface? Where whould you place SearchCriteria class?
I think it looks nice. It clearly signals that the SearchCriteria is intended for use with ProductServices specifically.
Some people however, would argue that nested classes look a bit odd and claim that this would be an over design and that package-scope is good enough in most cases including this.
I would encourage you to use classes when you have methods that may require more or less nullable arguments; it gives you the ability to provide whatever you need without having to call a method like:
someMethod("foo", null, null, null, null, null, null, ..., "bar");
Using such mecanism, the method call would be something like :
someMethod(new ObjParam().setFoo("foo").setBar("bar"));
The second method is expendable and reusable (without a tons of method overrides). And I'm not saying here that method override is bad! Quite the opposite. However with many optional arguments, I would prefer the second call.
As for inner classes, they are useful at times, but I personally follow these guidelines:
try to use inner classes only when the inner class should be private (ex: in the case of a custom LinkedList implementation, the Node class is a private class and is therefore an inner class.)
usually only if the class is not reusable and used mainly within a (very) small group of classes that I will make it an inner class
The "parent" and inner class becomes big enough; then both class are given their own Java source file for readability, unless the inner class should be private as for the first point.
Keep in mind that, inner class or not, the Java compiler will create a .class for every class. The more you use them, less readable your code will be. It's pretty much up to you to decide whether or not they're justified or not...
It's not bad, and can be useful if you want a tighter grouping between interfaces and some utility objects, like comparators. (I've done exactly the same with an interface, and inner classes providing useful comparators that compare instances of the interface.)
it can be a little awkward for clients to use, since they must prefix the inner class name with the interface name (or use a static import), but a good IDE takes care of this for you (but the code can be peppered with Interface.SomeClass declarations, which doesn't look so nice.)
However, in the specific case, SearchCriteria looks not so tightly coupled to the interface, so it may be more usable as a regular package class.
I'm afraid I'd like to vote for bad. Fairly bad anyway, you can do worse things...
For simplicity, a class should aim for one responsibility only. Your ProductService implementation has a criteria class definition within it, so when you wander through the code you must be aware of what part of the file you're in.
More importantly, separating makes the code of the entities involved simpler and more explicit. For me, this overrides all other concerns (ah, apart from the code being correct of course). I find simplicity & explictness are most helpful when it comes to retaining my hair, or at least that of the people who will maintain the stuff...

Categories

Resources