Preventing API users from using some methods - java

Hi I'm implementing a given design in java. Basically I have an abstract class which is called base and I have a number of concrete classes which are extending Base and implementing an interface from a different package. Each concrete class will be implementing a different interface. Now these interfaces contain both event-based and non event-based method signatures in them. My question here is; I'm only expected to implement non-event based methods in my concrete classes, however because of the implements keyword java forces me to insert an auto generated method body, which is basically return null. They might be implementing those event based methods later on but not at the moment. What would be an appropriate way to let the API user know that these methods do not contain an implementation. Here are my thoughts;
Use deprecated keyword
Create an exception class and throw that exception inside of the method and let the API user handle it.
I do not have the option of making changes to the existing architecture. Any idea really appreciated. Thank you.

According to Oracle, the reasons to deprecate an API include
It is insecure, buggy, or highly inefficient
It is going away in a future release
It encourages bad coding practices
neither of which actually fits your case.
Personally, I would favor throwing an UnsupportedOperationException which is already provided by the Standard Library in order to
indicate that the requested operation is not supported.
To me, this sounds more like what you actually want.

You can create your own interface which lists all the method you want users of your component to be able to access. Make this the only interface they use and additional public methods will not be visible.

Option (2) is good, but as you are following interfaces you'll want unchecked exceptions. And document the methods as unimplemented.
Deprecated implies a history, i.e., it works but should no longer be used. Since you are explicitly stating that the methods do not work, marking as deprecated will not prevent use nor indicate that the methods are unimplemented.

I would suggest use some mix bag of design patterns. That will help you solve this problem efficiently and make the code maintainable as well.
Based on my knowledge, you can use the Abstract Factory pattern here. See the design sketch below in the figure.
Method1 and method2 in subclass1 and subclass2 are the ones which are supposed to be exposed while method3 and method4 in subclass1 and subclass2 are the ones which we don't want to expose.
Create a Genericsubclass interface and create some methods in this interface depending upon the nature of methods you have in subclasses. For ex: i have create one method in this interface called nonEventbasedmethod1
Create a factory corresponding to every sub class and each factory will implement the GenericSubclass interface. Then implementation of nonEventbasedmethod1 method in subclass1Factory would be some thing like
nonEventbasedmethod1(){
subclass1.method1();
}
and implementation of nonEventbasedmethod1 method in subclass2Factory would be some thing like
nonEventbasedmethod1(){
subclass2.method3();
}
Then create a SubclassAbstract Factory which will return one of the subclass factories and then without worrying about which factory has been returned (that decision has already been taken in SubclassAbstractFactory before returning the appropriate factory) simply call the desired method from GenericSubclass interface and underneath one of the methods from the subclass1 or subclass2 will be invoked.
Hope this helps.

If you plain to throw an exception for "NotSupported" or "NotImplemented" Exception - consider the exception of NotImplementedException (at org.apache.commons).
However, I would reconsider to revisit your design and see if you can avoid having this - maybe you need to define another interface, which will hold the methods that are always implemented, and extend it in another interface (or provide an interface with no extension to the previous one) for the methods you not always implement.

Related

Override an interface?

I am creating a mod for the game Minecraft, which has an interface to implement in-game commands. I need the mod to implement that interface, but override one of its methods with a non-compatible method (different return type). But I need to prevent a situation where other classes that implement that interface will not work or not be recognized by the game.
I think this would require overriding the interface with a new interface that is the same as the original, but with an overloaded version of that method to support the mod's needs. Is this possible (or is there another way I can accomplish this?)
One way to think about interfaces is as a contract.
Implementing classes must strictly adhere to this contract.
This means that the method signatures (including return values and parameter) must match exactly.
The entire point of interfaces is to define the interaction without strictly knowing the implementation.
If the interaction you are looking to implement is different then it's possible that you are trying to use something in a way it wasn't intended for.
Even if it is possible to subclass an interface, it's going to quickly get messy.
It's probably in you best interest to create a new interface (with all the other methods the same).
Since it's not going to be comparable with classes that use interface A, you are saving yourself trouble by separating it entirely.
The interfaces supplied by Mojang/forge team are intended for use within the mojang/forge code. They expect the result types to be returned that the interfaces return. If they don't get that as defined by the contract/interface the code will crash/not compile.
It seems as if you are trying to use an interface for a particular purpose for an own project/api.
Consider writing a new interface specifically for the purpose you intend to use it for. Don't modify core interfaces.
A class can inherit multiple interfaces, so that's not an issue. You can implement AND the forge/mojang interface AND your own.
You can implement the mod class. Then override the method. Also write another method which will overload the method in your implemented class. That way you won't have to change the interface.

Java Code Style -- Interfaces vs. Abstract Classes

A new collaborator of mine who was reviewing some code I'd written told me that she wasn't used to seeing interfaces used directly in Java code, e.g.:
public interface GeneralFoo { ... }
public class SpecificFoo implements GeneralFoo { ... }
public class UsesFoo {
GeneralFoo foo = new SpecificFoo();
}
instead, expecting to see
public interface GeneralFoo { ... }
public abstract class AbstractFoo implements GeneralFoo { ... }
public class SpecificFoo extends AbstractFoo { ... }
public class UsesFoo {
AbstractFoo foo = new SpecificFoo();
}
I can see when this pattern makes sense, if all SpecificFoos share functionality through AbstractFoo, but if the various Foos have entirely different internal implementations (or we don't care how a specific Foo does Bar, as long as it does it), is there any harm in using an interface directly in code? I realize this is probably a tomato/tomato thing to some extent, but I'm curious if there's an advantage to the second style, or disadvantage to the first style, that I'm missing.
If you have no need for an abstract class with certain details common to all implementations, then there's no real need for an abstract class. Complexity often gets added to applications because there is some perceived need to support future features that haven't yet been defined. Stick with what works, and refactor later.
No, she's inexperienced, not right. Using interfaces is preferred, and writing redundant abstract super classes for the sake of redundancy is redundant.
UsesFoo should care about the behaviour specified by the interface, not about the super class of its dependencies.
For me "she wasn't used to" is not good enough reason. Ask her to elaborate on that.
Personally I'd use your solution, because:
AbstractFoo is redundant and ads no value in current situation.
Even if AbstractFoo was needed (for some additional functionality), I'd always use lowest needed type: if GeneralFoo was sufficient, then I'd use that, not some class derived from it.
It depends only on your problem.
If you use interfaces only, then if all your classes have a same method, it would have to be implemented redundantly (or moved away to a Util class).
On the other hand, if you do write an intermediary abstract class, you solved that problem, but now your subclass may not be a subclass of another class, because of absence of multiple inheritance in Java. If it was already necessary to extend some class, this is not possible.
So, shortly - it's a trade off. Use whichever is better in your particular case.
There is not harm in directly using an interface in code. If there were, Java would not have interfaces.
The disadvantages of using an interface directly include not being able to reach and class-specific methods which are not implemented in the interface. For poorly written interfaces, or classes which add a lot of "other" functionality, this is undesirable as you lose the ability to get to needed methods. However, in some cases this might be a reflection of a poor design choice in creating the interface. Without details it is too hard to know.
The disadvantages of using the base class directly include eventually ignoring the interface as it is not frequently used. In extreme cases, the interface becomes the code equivalent of a human appendix; "present but providing little to no functionality". Unused interfaces are not likely to be updated, as everyone will just use the base abstract class directly anyway. This allows your design to silently rot from the viewpoint of anyone who actually tries to use the interface. In extreme cases, it is not possible to handle an extending class through the interface to perform some critical functionality.
Personally, I favor returning classes via their interface and internally storing in members them via their lowest sub-class. This provides intimate knowledge of the class within the class's encapsulation, forces people to use the interface (keeping it up-to-date) externally, and the class's encapsulation allows possible future replacement without too much fuss.
I'm curious if there's an advantage to the second style, or disadvantage to the first style, that I'm missing
That reasons for the first interfaces style:
Often, the design is such that the interface is the public interface of the concept while the abstract class is an implementation detail of the concept.
For example, consider List and AbstractList in the collection framework. List is really what clients are usually after; fewer people know about about AbstractList because its an implementation detail to aid suppliers (implementers) of the interface), not clients (users) of the class.
The interface is looser coupling, therefore more flexible to support future changes.
Use the one that more clearer represents the requirement of the class, which is often the interface.
For example, List is often used rather than AbsrtactList or ArrayList. Using the interface, it may be clearer to a future maintainer that this class needs some kind of List, but it does not specifically need an AbstractList or an ArrayList. If this class relied on some AbstractList-specific property, i.e. it needs to use an AbstractList method, then using AbstractList list = ... instead of List list = ... may be a hint that this code relies on something specific to an AbstractList .
It may simplify testing/mocking to use the smaller, more abstract interface rather than to use the abstract class.
It is considered a bad practice by some to declare variables by their AbstractFoo signatures, as the UsesFoo class is coupled to some of the implementation details of foo.
This leads to less flexibility - you can not swap the runtime type of foo with any class that implements the GeneralFoo interface; you can only inject instances that implement the AbstractFoo descendant - leaving you with a smaller subset.
Ideally it should be possible for classes like UsesFoo to only know the interfaces of the collaborators they use, and not any implementation details.
And of course, if there is no need to declare anything abstract in a abstract class AbstractFoo implements GeneralFoo - i.e. no common implementation that all subclasses will re-use - then this is simply a waste of an extra file and levels in your hierarchy.
Firstly I use abstract and interface classes plentifully.
I think you need to see value in using an interface before using it. I think the design approach is, oh we have a class therefore we should have an abstract class and therefore we should have interfaces.
Firstly why do you need an interface, secondly why do you have an abstract class. It seems she may be adding things, for adding things sake. There needs to be clear value in the solution otherwise you are talking about code that has no value.
Emperically there you should see the value in her solution. If there is no value the solution is wrong, if it cant be explained to you she does not understand why she is doing it.
Simple code is the better solution and refactor when you need the complexity, flexibility or whatever perceived value she is getting from the solution.
Show the value or delete the code!
Oh one more thing have a look at the Java library code. Does that use the abstract / interface pattern that she is applying .. NO!

100% Abstract class vs Interface

Is there a reason to use a 100% abstract class and not an interface ?
Can you give me a good example when to use both so I can grasp the concept a little?
Update:
100% Abstract class -> abstract class with only abstract methods.
I'm curios if there are differences between php and java regarding this aspect.
Update2:
Even if I understand most of the reasons I'm more interested in the conceptual more than technical reasons.
If by "100% abstract class" you mean "abstract class with no concrete methods", then I can think of a reason: visibility.
You can define an abstract method to be protected, and hence not part of the public API of the class. However, that seems like an odd design.
Another thing that came to my mind is when you expect to add common functionality to the base class - i.e. if it is likely to have some utility methods shared by all implementors, but these methods are not implemented.
Another thing - instance variables. You can have inheritable instance variables in the abstract class.
The one case where an "100% abstract class" may be advantageous over an interface is in places where API stability is a key concern.
If you write an API where other people are expected to implement your interface you have to stick to the interface. You can't add any methods to the interface later on because that would break all clients (you would have to work around this by implement a second interface and let your code check againt the usage with instanceof checks and provide an fallback).
If you realize the same with an class you can add (non abstract) methods later on without breaking the client.
Next to visibility, another reason could be to be able to specify a certain Constructor you want all implementations to implement, or define a certain property. But in general, I agree with Alexander that a 100% abstract class isn't a good idea. I would prefer an interface in most cases unless there's a very good reason not to use an interface.
I personally think the difference as conceptual more than technical. For instance it would be bad idea to have an interface called "Human" and implement them on Male and Female. It would make more sense to make the Human as class.
You can implement multiple interfaces and you should see interfaces as add-ons.
I'm not quite sure how to answer this conceptually anymore, but in practice I use interfaces for the following reasons:
To indicate different classes have a shared interface: that you can manipulate them / use them in the same way
You can implement multiple interfaces, but only extend one class
Reasons for using abstract classes:
To share functionality between similar objects. For example Porshe911 could extend Car, overwrite a few methods and keep the rest.
To write frameworks that people can adapt. For example by leaving a few crucial methods unimplemented and writing the rest of the class to be internally consistent provided you implement those few methods. An example would be a menu class with a single abstract method getMenuItems()
Your example of the 100% abstract class seems senseless to me. As far as I can see that would just make it an interface, with the added restriction that you can have only one.
100% Abstract class isn't good idea. For common structure of child classes uses Interface. For similiar classes with same some methods and not same others more better to use Abstract Class.

Coding to interfaces? [duplicate]

This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 9 years ago.
I want to solidify my understanding of the "coding to interface" concept. As I understand it, one creates interfaces to delineate expected functionality, and then implements these "contracts" in concrete classes. To use the interface one can simply call the methods on an instance of the concrete class.
The obvious benefit is knowing of the functionality provided by the concrete class, irrespective of its specific implementation.
Based on the above:
Are there any fallacies in my understanding of "coding to interfaces"?
Are there any benefits of coding to interfaces that I missed?
Thanks.
Just one possible correction:
To use the interface one can simply call the methods on an instance of the concrete class.
One would call the methods on a reference of the type interface, which happens to use the concrete class as implementation:
List<String> l = new ArrayList<String>();
l.add("foo");
l.add("bar");
If you decided to switch to another List implementation, the client code works without change:
List<String> l = new LinkedList<String>();
This is especially useful for hiding implementation details, auto generating proxies, etc.
You'll find that frameworks like spring and guice encourage programming to an interface. It's the basis for ideas like aspect-oriented programming, auto generated proxies for transaction management, etc.
Your understanding seems to be right on. Your co-worker just swung by your desk and has all the latest pics of the christmas party starring your drunk boss loaded onto his thumbdrive. Your co-worker and you do not think twice about how this thumbdrive works, to you its a black box but you know it works because of the USB interface.
It doesn't matter whether it's a SanDisk or a Titanium (not even sure that is a brand), size / color don't matter either. In fact, the only thing that matters is that it is not broken (readable) and that it plugs into USB.
Your USB thumbdrive abides by a contract, it is essentially an interface. One can assume it fulfills some very basic duties:
Plugs into USB
Abides by the contract method CopyDataTo:
public Interface IUSB {
void CopyDataTo(string somePath); //used to copy data from the thumbnail drive to...
}
Abides by the contract method CopyDataFrom:
public Interface IUSB {
void CopyDataFrom(); //used to copy data from your PC to the thumbnail drive
}
Ok maybe not those methods but the IUSB interface is just a contract that the thumbnail drive vendors have to abide by to ensure functionality across various platforms / vendors. So SanDisk makes their thumbdrive by the interface:
public class SanDiskUSB : IUSB
{
//todo: define methods of the interface here
}
Ari, I think you already have a solid understanding (from what it sounds like) about how interfaces work.
The main advantage is that the use of an interface loosely couples a class with it's dependencies. You can then change a class, or implement a new concrete interface implementation without ever having to change the classes which depend on it.
To use the interface one can simply call the methods on an instance of the concrete class.
Typically you would have a variable typed to the interface type, thus allowing only access to the methods defined in the interface.
The obvious benefit is knowing of the functionality provided by the concrete class, irrespective of its specific implementation.
Sort of. Most importantly, it allows you to write APIs that take parameters with interface types. Users of the API can then pass in their own classes (which implement those interfaces) and you code will work on those classes even though they didn't exist yet when it was written (such as java.util.Arrays.sort() being able to sort anything that implements Comparable or comes with a suitable Comparator).
From a design perspective, interfaces allow/enforce a clear separation between API contracts and implementation details.
The aim of coding against interfaces is to decouple your code from the concrete implementation in use. That is, your code will not make assumptions about the concrete type, only the interface. Consequently, the concrete implementation can be exchanged without needing to adjust your code.
You didn't list the part about how you get an implementation of the interface, which is important. If you explicitly instantiate the implementing class with a constructor then your code is tied to that implementation. You can use a factory to get an instance for you but then you're as tied to the factory as you were before to the implementing class. Your third alternative is to use dependency injection, which is having a factory plug the implementing object into the object that uses it, in which case you escape having the class that uses the object being tied to the implementing class or to a factory.
I think you may have hinted at this, but I believe one of the biggest benefits of coding to an interface is that you are breaking dependency on concrete implementation. You can achieve loose coupling and make it easier to switch out specific implementations without changing much code. If you are just learning, I would take a look at various design patterns and how they solve problems by coding to interfaces. Reading the book Head First: Design Patterns really helped things click for me.
As I understand it, one creates interfaces to delineate expected functionality, and then implements these "contracts" in concrete classes.
The only sort of mutation i see in your thinking is this - You're going to call out expected contracts, not expected functionality. The functionality is implemented in the concrete classes. The interface only states that you will be able to call something that implements the interface with the expected method signatures. Functionality is hidden from the calling object.
This will allow you to stretch your thinking into polymorphism as follows.
SoundMaker sm = new Duck();<br/>
SoundMaker sm1 = new ThunderousCloud();
sm.makeSound(); // quack, calls all sorts of stuff like larynx, etc.<br/>
sm1.makeSound(); // BOOM!, completely different operations here...

Why are interfaces preferred to abstract classes?

I recently attended an interview and they asked me the question "Why Interfaces are preferred over Abstract classes?"
I tried giving a few answers like:
We can get only one Extends functionality
they are 100% Abstract
Implementation is not hard-coded
They asked me take any of the JDBC api that you use. "Why are they Interfaces?".
Can I get a better answer for this?
That interview question reflects a certain belief of the person asking the question. I believe that the person is wrong, and therefore you can go one of two directions.
Give them the answer they want.
Respectfully disagree.
The answer that they want, well, the other posters have highlighted those incredibly well.
Multiple interface inheritance, the inheritance forces the class to make implementation choices, interfaces can be changed easier.
However, if you create a compelling (and correct) argument in your disagreement, then the interviewer might take note.
First, highlight the positive things about interfaces, this is a MUST.
Secondly, I would say that interfaces are better in many scenarios, but they also lead to code duplication which is a negative thing. If you have a wide array of subclasses which will be doing largely the same implementation, plus extra functionality, then you might want an abstract class. It allows you to have many similar objects with fine grained detail, whereas with only interfaces, you must have many distinct objects with almost duplicate code.
Interfaces have many uses, and there is a compelling reason to believe they are 'better'. However you should always be using the correct tool for the job, and that means that you can't write off abstract classes.
In general, and this is by no means a "rule" that should be blindly followed, the most flexible arrangement is:
interface
abstract class
concrete class 1
concrete class 2
The interface is there for a couple of reasons:
an existing class that already extends something can implement the interface (assuming you have control over the code for the existing class)
an existing class can be subclasses and the subclass can implement the interface (assuming the existing class is subclassable)
This means that you can take pre-existing classes (or just classes that MUST extend from something else) and have them work with your code.
The abstract class is there to provide all of the common bits for the concrete classes. The abstract class is extended from when you are writing new classes or modifying classes that you want to extend it (assuming they extend from java.lang.Object).
You should always (unless you have a really good reason not to) declare variables (instance, class, local, and method parameters) as the interface.
You only get one shot at inheritance. If you make an abstract class rather than an interface, someone who inherits your class can't also inherit a different abstract class.
You can implement more than one interface, but you can only inherit from a single class
Abstract Classes
1.Cannot be instantiated independently from their derived classes. Abstract class constructors are called only by their derived classes.
2.Define abstract member signatures that base classes must implement.
3.Are more extensible than interfaces, without breaking any version compatibility. With abstract classes, it is possible to add additional nonabstract members that all derived classes can inherit.
4.Can include data stored in fields.
5.Allow for (virtual) members that have implementation and, therefore, provide a default implementation of a member to the deriving class.
6.Deriving from an abstract class uses up a subclass's one and only base class option.
Interface
1.Cannot be instantiated.
2.Implementation of all members of the interface occurs in the base class. It is not possible to implement only some members within the implementing class.
3.Extending interfaces with additional members breaks the version compatibility.
4.Cannot store any data. Fields can be specified only on the deriving classes. The workaround for this is to define properties, but without implementation.
5.All members are automatically virtual and cannot include any implementation.
6.Although no default implementation can appear, classes implementing interfaces can continue to derive from one another.
As devinb and others mention, it sounds like the interviewer shows their ignorance in not accepting your valid answers.
However, the mention of JDBC might be a hint. In that case, perhaps they are asking for the benefits of a client coding against an interface instead of a class.
So instead of perfectly valid answers such as "you only get one use of inheritance", which are relating to class design, they may be looking for an answer more like "decouples a client from a specific implementation".
Abstract classes have a number of potential pitfalls. For example, if you override a method, the super() method is not called unless you explicitly call it. This can cause problems for poorly-implemented overriding classes. Also, there are potential problems with equals() when you use inheritance.
Using interfaces can encourage use of composition when you want to share an implementation. Composition is very often a better way to reuse others objects, as it is less brittle. Inheritance is easily overused or used for the wrong purposes.
Defining an interface is a very safe way to define how an object is supposed to act, without risking the brittleness that can come with extending another class, abstract or not.
Also, as you mention, you can only extend one class at a time, but you can implement as many interfaces as you wish.
Abstract classes are used when you inherit implementation, interfaces are used when you inherit specification. The JDBC standards state that "A connection must do this". That's specification.
When you use abstract classes you create a coupling between the subclass and the base class. This coupling can sometimes make code really hard to change, especially as the number of subclasses increases. Interfaces do not have this problem.
You also only have one inheritance, so you should make sure you use it for the proper reasons.
"Why Interfaces are preferred over
Abstract classes?"
The other posts have done a great job of looking at the differences between interfaces and abstract classes, so I won't duplicate those thoughts.
But looking at the interview question, the better question is really "When should interfaces be preferred over abstract classes?" (and vice versa).
As with most programming constructs, they're available for a reason and absolute statements like the one in the interview question tend to miss that. It sort of reminds me of all the statement you used to read regarding the goto statement in C. "You should never use goto - it reveals poor coding skills." However, goto always had its appropriate uses.
Respectfully disagree with most of the above posters (sorry! mod me down if you want :-) )
First, the "only one super class" answer is lame. Anyone who gave me that answer in an interview would be quickly countered with "C++ existed before Java and C++ had multiple super classes. Why do you think James Gosling only allowed one superclass for Java?"
Understand the philosophy behind your answer otherwise you are toast (at least if I interview you.)
Second, interfaces have multiple advantages over abstract classes, especially when designing interfaces. The biggest one is not having a particular class structure imposed on the caller of a method. There is nothing worse than trying to use a method call that demands a particular class structure. It is painful and awkward. Using an interface anything can be passed to the method with a minimum of expectations.
Example:
public void foo(Hashtable bar);
vs.
public void foo(Map bar);
For the former, the caller will always be taking their existing data structure and slamming it into a new Hashtable.
Third, interfaces allow public methods in the concrete class implementers to be "private". If the method is not declared in the interface then the method cannot be used (or misused) by classes that have no business using the method. Which brings me to point 4....
Fourth, Interfaces represent a minimal contract between the implementing class and the caller. This minimal contract specifies exactly how the concrete implementer expects to be used and no more. The calling class is not allowed to use any other method not specified by the "contract" of the interface. The interface name in use also flavors the developer's expectation of how they should be using the object. If a developer is passed a
public interface FragmentVisitor {
public void visit(Node node);
}
The developer knows that the only method they can call is the visit method. They don't get distracted by the bright shiny methods in the concrete class that they shouldn't mess with.
Lastly, abstract classes have many methods that are really only present for the subclasses to be using. So abstract classes tend to look a little like a mess to the outside developer, there is no guidance on which methods are intended to be used by outside code.
Yes of course some such methods can be made protected. However, sadly protected methods are also visible to other classes in the same package. And if an abstract class' method implements an interface the method must be public.
However using interfaces all this innards that are hanging out when looking at the abstract super class or the concrete class are safely tucked away.
Yes I know that of course the developer may use some "special" knowledge to cast an object to another broader interface or the concrete class itself. But such a cast violates the expected contract, and the developer should be slapped with a salmon.
If they think that X is better than Y I wouldn't be worried about getting the job, I wouldn't like working for someone who forced me to one design over another because they were told interfaces are the best. Both are good depending on the situation, otherwise why did the language choose to add abstract classes? Surely, the language designers are smarter than me.
This is the issue of "Multiple Inheritance".
We can "extends" not more than one abstarct class at one time through another class but in Interfaces, we can "implement" multiple interfaces in single class.
So, though Java doesn't provide multiple inheritance in general but by using interfaces we can incorporate multiplt inheritance property in it.
Hope this helps!!!
interfaces are a cleaner way of writing a purely abstract class. You can tell that implementation has not sneaked in (of course you might want to do that at certain maintenance stages, which makes interfaces bad). That's about it. There is almost no difference discernible to client code.
JDBC is a really bad example. Ask anyone who has tried to implement the interfaces and maintain the code between JDK releases. JAX-WS is even worse, adding methods in update releases.
There are technical differences, such as the ability to multiply "inherit" interface. That tends to be the result of confused design. In rare cases it might be useful to have an implementation hierarchy that is different from the interface hierarchy.
On the downside for interfaces, the compiler is unable to pick up on some impossible casts/instanceofs.
There is one reason not mentioned by the above.
You can decorate any interface easily with java.lang.reflect.Proxy allowing you to add custom code at runtime to any method in the given interface. It is very powerful.
See http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html for a tutorial.
interface is not substitute for abstract class.
Prefer
interface: To implement a contract by multiple unrelated objects
abstract class: To implement the same or different behaviour among multiple related objects
Refer to this related SE question for use cases of both interface and abstract class
Interface vs Abstract Class (general OO)
Use case:
If you have to use Template_method pattern, you can't achieve with interface. Abstract class should be chosen to achieve it.
If you have to implement a capability for many unrleated objects, abstract class does not serve the purpose and you have to chose interface.
You can implement multiple interfaces, but particularly with c# you can not have multiple inheritances
Because interfaces are not forcing you into some inheritance hierarchy.
You define interfaces when you only require that some object implement certain methods but you don't care about its pedigree. So someone can extend an existing class to implement an interface, without affecting the previously existing behavior of that class.
That's why JDBC is all interfaces; you don't really care what classes are used in a JDBC implementation, you only need any JDBC implementation to have the same expected behavior. Internally, the Oracle JDBC driver may be very different from the PostgreSQL driver, but that's irrelevant to you. One may have to inherit from some internal classes that the database developers already had, while another one may be completely developed from scratch, but that's not important to you as long as they both implement the same interfaces so that you can communicate with one or the other without knowing the internal workings of either.
Well, I'd suggest the question itself should be rephrased. Interfaces are mainly contracts that a class acquires, the implementation of that contract itself will vary. An abstract class will usually contain some default logic and its child classes will add some more logic.
I'd say that the answer to the questions relies on the diamond problem. Java prevents multiple inheritance to avoid it. ( http://en.wikipedia.org/wiki/Diamond_problem ).
They asked me take any of the JDBC api
that you use. "Why are they
Interfaces?".
My answer to this specific question is :
SUN doesnt know how to implement them or what to put in the implementation. Its up to the service providers/db vendors to put their logic into the implementation.
The JDBC design has relationship with the Bridge pattern, which says "Decouple an abstraction from its implementation so that the two can vary independently".
That means JDBC api's interfaces hierarchy can be evolved irrespective of the implementation hierarchy that a jdbc vendor provides or uses.
Abstract classes offer a way to define a template of behavior, where the user plugins in the details.
One good example is Java 6's SwingWorker. It defines a framework to do something in the background, requiring the user to define doInBackground() for the actual task.
I extended this class such that it automatically created a popup progress bar. I overrode done(), to control disposal of this pop-up, but then provided a new override point, allowing the user to optionally define what happens after the progress bar disappears.
public abstract class ProgressiveSwingWorker<T, V> extends SwingWorker<T, V> {
private JFrame progress;
public ProgressiveSwingWorker(final String title, final String label) {
SwingUtilities.invokeLater(new Runnable() {
#SuppressWarnings("serial")
#Override
public void run() {
progress = new JFrame() {{
setLayout(new MigLayout("","[grow]"));
setTitle(title);
add(new JLabel(label));
JProgressBar bar = new JProgressBar();
bar.setIndeterminate(true);
add(bar);
pack();
setLocationRelativeTo(null);
setVisible(true);
}};
}
});
}
/**
* This method has been marked final to secure disposing of the progress dialog. Any behavior
* intended for this should be put in afterProgressBarDisposed.
*/
#Override
protected final void done() {
progress.dispose();
try {
afterProgressBarDisposed(get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
protected void afterProgressBarDisposed(T results) {
}
}
The user still has the requirement of providing the implementation of doInBackground(). However, they can also have follow-up behavior, such as opening another window, displaying a JOptionPane with results, or simply do nothing.
To use it:
new ProgressiveSwingWorker<DataResultType, Object>("Editing some data", "Editing " + data.getSource()) {
#Override
protected DataResultType doInBackground() throws Exception {
return retrieve(data.getSource());
}
#Override
protected void afterProgressBarDisposed(DataResultType results) {
new DataEditor(results);
}
}.execute();
This shows how an abstract class can nicely provide a templated operation, orthogonal to the concept of interfaces defining an API contract.
Its depend on your requirement and power of implementation, which is much important.
You have got so many answer regarding this question.
What i think about this question is that abstract class is the evolution if API.
You can define your future function definition in abstract class but you don't need all function implementation in your main class but with interface you cant do this thing.

Categories