Any examples of bad uses of interface? - java

I want to avoid use interface when it's not needed. For example, there is an interface AAA, and there is a class AAAImpl implementing it, this interface AAA is only being implemented by AAAImpl, and AAAImpl is only implementing one interface, which is this AAA. The argument of doing this is the code is decoupled, it will be easier for unit testing, it leaves more options in the future for adding more features, etc.
Are these arguments valid?

One class implementing one interface is a perfectly valid strategy for designing a class library, as long as the users of your class have no direct access to the implementing class. This is information hiding at its best: the users see what they need to see, while you keep an ability to redesign your implementation in more ways than you could if you let the users access the implementing class directly.
This also gives your users the flexibility to test their code without relying on any of your code outside the interface definition.
Overall, it is a win-win situation with no downsides.
As far as bad uses of interfaces go, there is a number of possibilities:
Interfaces that attempt to do too much - Adding an interface that covers every single method of a class that performs many different tasks is a bad idea, with the exception of "infrastructure interfaces", e.g. interfaces required to define remoting.
Interfaces that attempt to do too little - Such interfaces cover a small part of functionality of the class, without enabling a meaningful task to be performed without making a reference to the implementing class.
Interfaces that provide a poor match for the functionality of the class - for example, adding IComparable<T> or IEquitable<T> to a mutable class.

One of the bad usege of interface is when iterface has more then it's needed and classes which implement the interface will have to implement all those methods which normally shouldn't.
For example, we have interface for printing and we have many different version of printing (from html document without footer, from html doc with footer, from pdf etc).
So our interface will look like:
public interface IPrinter{
public void printHtmlWithFooter();
public void printHtmlWithoutFooter();
public void printPdf();
}
and then you have implementations:
public class HtmlPrinter implements IPrinter{
public void printHtmlWithFooter(){
// some code, printing ....
}
public void printHtmlWithoutFooter(){
// some code, printing ....
}
public void printPdf(){}
}
public class PdfPrinter implements IPrinter{
public void printHtmlWithFooter(){}
public void printHtmlWithoutFooter(){}
public void printPdf(){
// some code, printing ....
}
}
as you see, you need to implement all of these methods in each class even if they are completely empty. Let's imagine that you have 10 different classes which implement IPrinter interface and you want to add one additional method into interface, so you need to do implementation in each of these classes.
That would be one of examples how you should not use interfaces.
Instead of that you should have only:
public interface IPrinter{
public void print();
}
and then client doesn't care how it will be printed and what, he only knows that method print() has to be called and that's it. Concrete classes should take care about concrete implementation.

Related

Can interfaces evolve with time?

Interfaces are great from a flexibility standpoint. But in case, where an interface is used by a large number of clients. Adding new methods to the interface while keeping the old mehtods intact will break all clients' code as new methods won't be present in clients. As shown below:
public interface CustomInterface {
public void method1();
}
public class CustomImplementation implements CustomInterface {
#Override
public void method1() {
System.out.println("This is method1");
}
}
If at some point later in time, we add another method to this interface all clients' code will break.
public interface CustomInterface {
public void method1();
public void method2();
}
To avoid this we have to explicitly implement new methods in all clients' code.
So I think of interfaces and this scenario as following:
Interfaces once written are like carving in stone. They are rarely supposed, and expected to change. And if they do, they come with a huge cost(rewriting the whole code) which programmers should be ready for.
In continuation with the point above, Is it possible to write interfaces that can stand the test of time?
How such a scenario is handled in interfaces where you expect additional functionality in future? That is anticipating change in the contract by which all clients are binded.
EDIT: Default method is indeed a nice addition to Java Interfaces which a lot of people have mentioned in their answers. But my question was more in the context of code design. And how forcing method implementation on the client is an intrinsic character of an interface. But this contract between an interface and a client seems fragile as functionality will eventually evolve.
One solution to this problem was introduced in Java 8 in the form of default methods in interfaces. It allowed to add new methods to existing Java SE interfaces without breaking existing code, since it supplied default implementation to all the new methods.
For example, the Iterable interface, which is widely used (it's a super interface of the Collection interface) was added two new default methods - default void forEach(Consumer<? super T> action) and default Spliterator<T> spliterator().
public interface CustomInterface {
public void method1();
}
public interface CustomInterface2 extends CustomInterface {
public void meathod2();
}
Other than default method you can use inheritance property as show above by which new interface will have all previous method along with new methods and use this interface in your required situation.
Java 8 has introduced default implementation for methods. These implementations reside in the interface. If a new method with a default implementation is created in an interface that is already implemented by many classes, there is no need to modify all the classes, but only the ones that we want to have a different implementation for the newly defined method than the default one.
Now, what about older Java versions? Here we can have another interface that extends the first one. After that, classes that we want to implement the newly-declared method will be changed to implement the new interface. As shown below.
public interface IFirst {
void method1();
}
public class ClassOne implements IFirst() {
public void method1();
}
public class ClassTwo implements IFirst() {
public void method1();
}
Now, we want method2() declared, but it should only be implemented by ClassOne.
public interface ISecond extends iFirst {
void method2();
}
public class ClassOne implements ISecond() {
public void method1();
public void method2();
}
public class ClassTwo implements IFirst() {
public void method1();
}
This approach will be ok in most cases, but it does have downsides as well. For example, we want method3() (and only that one) for ClassTwo. We will need a new interface IThird. If later we will want to add method4() that should be implemented by both ClassOne and ClassTwo, we will need to modify (but not ClassThree that also implemented IFirst) we will need to change both ISecond and IThird.
There rarely is a "magic bullet" when it comes to programming. In the case of interfaces, it is best if they don't change. This isn't always the case in real-life situations. That is why it is advised that interfaces offer just "the contract" (must-have functionality) and when possible use abstract classes.
A future interface change shouldn't break anything that has been working -- if it does, it's a different interface. (It may deprecate things, though, and a full cycle after deprecation it may be acceptable to say that throwing an Unimplemented exception is acceptable.)
To add things to an interface, the cleanest answer is to derive a new interface from it. That will allow using objects implementing the new behaviors with code expecting the old ones, while letting the user declare appropriately and/or typecast to get access to the new features. It's a bit annoying since it may require instanceof tests, but it's the most robust approach, and it's the one you'll see in many industry standards.
Interfaces are contracts between the developer and clients, so you're right - they are carved in stone and should not be changed. Therefore, an interface should expose (= demand) only the basic functionality that's absolutely required from a class.
Take the List interface for example. There are many implementations of lists in Java, many of which evolve over time (better under-the-hood algorithms, improved memory storage), but the basic "concept" of a list - add an item, search for an item, remove an item - should not and will not ever change.
So, to your question: Instead of writing interfaces which classes implement, you can use abstract classes. Interfaces are basically purely-abstract classes, in the sense that they do not provide any built-in functionality. However, one can add new, non-abstract methods to an abstract class that clients will not be required to implement (override).
Take this abstract class (= interface) for example:
abstract class BaseQueue {
abstract public Object pop();
abstract public void push(Object o);
abstract public int length();
public void clearEven() {};
}
public class MyQueue extends BaseQueue {
#Override
public Object pop() { ... }
...
}
Just like in interfaces, every class that extends BaseQueue is contractually bound to implement the abstract methods. The clearEven() method, however, is not an abstract method (and already comes with an empty implementation), so the client is not forced to implement it, or even use it.
That means that you can leverage the power of abstract classes in Java in order to create non-contractually-binding methods. You can add other methods to the base class in the future as much as you like, provided that they are not abstract methods.
I think your question is more about design and techniques, so java8 answers are a bit misleading. This problem was known long before java8, so there are some other solutions for it.
First, there are no absolutely chargeless ways to solve a problem. The size of inconviniences that come from interface evolving depends on how the library is used and how deliberate your design is.
1) No techniques will help, if you designed an interface and forgot to include a mandatory method in it. Plan your design better and try to anticipate how clients will use your interfaces.
Example: Imagine Machine interface that has turnOn() method but misses turnOff() method. Introducing a new method with default empty implementation in java8 will prevent compilation errors but will not really help, because calling a method will have no effect. Providing working implementation is sometimes impossible because interface has no fields and state.
2) Different implementations usually have things in common. Don't be afraid to keep common logic in parent class. Inherit your library classes from this parent class. This will enforce library clients to inherit their own implementations from your parent class as well. Now you can make small changes to the interface without breaking everything.
Example: You decided to include isTurnedOn() method to your interface. With a basic class, you can write a default method implementation that would make sence. Classes that were not inherited from parent class still need to provide their own method implementations, but since method is not mandatory, it will be easy for them.
3) Upgrading the functionality is usually achieved by extending the interfaces. There's no reason to force library clients to implement a bunch of new methods because they may not need them.
Example: You decided to add stayIdle() method to your interface. It makes sence for classes in your library, but not for custom client classes. Since this functionality is new, it's better to create a new interface that will extend Machine and use it when it's needed.

Why doesn't interfaces implement methods and override them?

I already read the post of research effort required to post a SO question. I am ashamed again to post this question to a pile of million questions. But I still don't get the idea of interfaces in java. They have unimplemented methods and then defined for every class in which they are implemented. I searched about it. Interfaces were used to support multiple inheritance in java and also to avoid (Deadly) Diamond Death of inheritance. I also came across Composition vs Inheritance and that inheritance is not for code reuse and its for polymorphism. So when I have a common code as a class to extend it will not be supported due to multiple inheritance which gives the option to use Interfaces(Correct me if I am wrong). I also came across that its not possible in most cases to define a generic implementation. So what is the problem in having a common definition (not a perfect generic implementation) of the interface method and then Override it wherever necessary and why doesn't java support it. Eg. When I have 100 classes that implements an interface 70 of them have a common implementation while others have different implementation. Why do I have to define the common method in interface over 70 classes and why can't I define them in Interface and then override them in other 30 classes which saves me from using same code in 70 classes. Is my understanding of interfaces wrong?
First, an interface in Java (as of Java 7) has no code. It's a mere definition, a contract a class must fulfill.
So what is the problem in having a common definition (not a perfect
generic implementation) of the interface method and then Override it
wherever necessary and why doesn't java support it
Yes you can do that in Java, just not with interfaces only. Let's suppose I want from this Example interface to have a default implementation for method1 but leave method2 unimplemented:
interface Example {
public void method1();
public String method2(final int parameter);
}
abstract class AbstractExampleImpl implements Example {
#Override
public void method1() {
// Implement
}
}
Now classes that want to use this method1 default implementation can just extend AbstractExampleImpl. This is more flexible than implementing code in the interface because if you do so, then all classes are bound to that implementation which you might not want. This is the advantage of interfaces: being able to reference a certain behavior (contract) without having to know how the class actually implements this, for example:
List<String> aList = MyListFactory.getNewList();
MyListFactory.getNewList() can return any object implementing List, our code manipulating aList doesn't care at all because it's based on the interface.
What if the class that uses interface already is a Sub-class. Then we
can't use Abstract class as multiple inheritance is not supported
I guess you mean this situation:
class AnotherClass extends AnotherBaseClass
and you want to extend AbstractExampleImpl as well. Yes, in this case, it's not possible to make AnotherClass extend AbstractExampleImpl, but you can write a wrapped inner-class that does this, for example:
class AnotherClass extends AnotherBaseClass implements Example {
private class InnerExampleImpl extends AbstractExampleImpl {
// Here you have AbstractExampleImpl's implementation of method1
}
}
Then you can just internally make all Example methods being actually implemented by InnerExampleImpl by calling its methods.
Is it necessary to have the interface in AnotherClass?
I guess you mean AnotherClass implements Example. Well, this is what you wanted: have AnotherClass implement Example with some default implementation as well as extend another class, or I understood you wrong. Since you cannot extend more than one class, you have to implement the interface so you can do
final Example anotherClass = new AnotherClass();
Otherwise this will not be possible.
Also for every class that implements an interface do I have to design
an inner class?
No, it doesn't have to be an inner class, that was just an example. If you want multiple other classes have this default Example implementation, you can just write a separate class and wrap it inside all the classes you want.
class DefaultExampleImpl implements Example {
// Implements the methods
}
class YourClass extends YetAnotherClass implements Example {
private Example example = new DefaultClassImpl();
#Override
public void method1() {
this.example.method1();
}
#Override
public String method2(final int parameter) {
return this.example.method2(parameter);
}
}
You can create an abstract class to implement that interface, and make your those classes inherit that abstract class, that should be what you want.
A non abstract class that implements and interface needs to implement all the methods from the interface. A abstract class doesn't have to implement all the methods but cannot initiated. If you create abstract class in your example that implements all the interface methods except one. The classes that extend from these abstract class just have to implement the one not already implemented method.
The Java interfaces could have been called contracts instead to better convey their intent. The declarer promise to provide some functionality, and the using code is guaranteed that the object provides that functionality.
This is a powerful concept and is decoupled from how that functionality is provided where Java is a bit limited and you are not the first to notice that. I have personally found that it is hard to provide "perfect" implementations which just need a subclass or two to be usable in a given situation. Swing uses adapters to provide empty implementations which can then be overrides as needed and that may be the technique you are looking for.
The idea of the interface is to create a series of methods that are abstract enough to be used by different classes that implement them. The concept is based on the DRY principle (Don't repeat yourself) the interface allows you to have methods like run() that are abstract enough to be usuable for a game loop, a players ability to run,
You should understand the funda of interface first. Which is
It is use to provide tight coupling means tight encapsulation
It helps us to hide our code from the external environment i.e. from other class
Interface should have only definition and data which is constant
It provide facility to class open for extension. Hence it cannot be replace by the any other class in java otherwise that class will become close for extension. which means class will not be able to extend any other class.
I think you are struggling with the concept of Object Oriented Design more than anything. In your example above where you state you have 100 classes and 70 of them have the same method implementation (which I would be stunned by). So given an interface like this:
public interface Printable
{
void print();
}
and two classes that have the "same" implementation of print
public class First implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
public class Second implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
you would instead want to do this:
public abstract class DefaultPrinter implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
now for First and Second
public class First extends DefaultPrinter
{
}
public class Second extends DefaultPrinter
{
}
Now both of these are still Printable . Now this is where it gets very important to understand how to properly design object hierarchies. If something IS NOT a DefaultPrinter YOU CANNOT AND SHOULD NOT make the new class extend DefaultPrinter

Why does all the interface methods need to be implemented in a class implementing it in java

I know that it is the purpose of the interface and the class can be declared abstract to escape from it.
But is there any use for implementing all the methods that we declare in an interface? will that not increase the weight and complexity of the code if we keep on defining all the methods even it is not relevant for that class? why it is designed so?
The idea of an interface in Java is very much like a contract (and perhaps seen in retrospect this should have been the name of the concept)
The idea is that the class implementing the interface solemnly promises to provide all the things listed in the contract so that any use of a class implementing the interface is guaranteed to have that functionality available.
In my experience this facility is one of the things that makes it possible to build cathedrals in Java.
What you are critizing is exactly the goal interface achieve.
If you don't want to implement an interface, don't declare your class implementing it.
will that not increase the weight and complexity of the code if we
keep on defining all the methods even it is not relevant for that
class?
When you program against an interface, you want the concrete object behind it to implement all its methods. If your concrete object doesn't need or cannot implement all interface method you probably have a design issue to fix.
When any piece of code receives an instance of an interface without knowing what class is behind it, that piece of code should be assured of the ability to call any method in an interface. This is what makes an interface a contract between the callers and the providers of the functionality. The only way to achieve that is to require all non-abstract classes implementing the interface to provide implementations for all its functions.
There are two general ways to deal with the need to not implement some of the functionality:
Adding a tester method and an implementation that throws UnsupportedOperationException, and
Splitting your interface as needed into parts so that all method of a part could be implemented.
Here is an example of the first approach:
public interface WithOptionalMehtods {
void Optional1();
void Optional2();
boolean implementsOptional1();
boolean implementsOptional2();
}
public class Impl implements WithOptionalMehtods {
public void Optional1() {
System.out.println("Optional1");
}
public void Optional2() {
throw new UnsupportedOperationException();
}
public boolean implementsOptional1() {
return true;
}
public boolean implementsOptional2() {
return false;
}
}
Here is an example of the second approach:
public interface Part1 {
void Optional1();
}
public interface Part2 {
void Optional2();
}
public Impl implements Part1 {
public void Optional1() {
System.out.println("Optional1");
}
}
will that not increase the weight and complexity of the code if we
keep on defining all the methods even it is not relevant for that
class?
Yes you are right it will. That is why it is best practice in your coding to follow the Interface Segregation Principle which recommends not to force clients to implement interfaces that they don't use. So you should never have one "fat" interface with many methods but many small interfaces grouping methods, each group serving a specific behavior or sub-module.
This way clients of an interface implement only the needed methods without ever being forced into implementing methods they don't need.
It may depend on Liskov Substitution Principle
So, having A implements B means that you can use A when B is needed and, to make it work without problems, A must have at least the same methods of B.
Please keep in mind that mine is not a "proper" answer, as it's not based on official sources!
When implementing an Interface,we may not need to define all the method declared in the Interface.We can define the some methods,that we don't need,With nothing inside the body.

How do Java Interfaces simulate multiple inheritance?

I am reading "The Java Tutorial" (for the 2nd time). I just got through the section on Interfaces (again), but still do not understand how Java Interfaces simulate multiple inheritance. Is there a clearer explanation than what is in the book?
Suppose you have 2 kinds of things in your domain : Trucks and Kitchens
Trucks have a driveTo() method and Kitchens a cook() method.
Now suppose Pauli decides to sell pizzas from the back of a delivery truck. He wants a thing where he can driveTo() and cook() with.
In C++ he would use multiple inheritance to do this.
In Java that was considered to be too dangerous so you can inherit from a main class, but you can "inherit" behaviors from interfaces, which are for all intents and purposes abstract classes with no fields or method implementations.
So in Java we tend to implement multiple inheritance using delegations :
Pauli subclasses a truck and adds a kitchen to the truck in a member variable called kitchen. He implements the Kitchen interface by calling kitchen.cook().
class PizzaTruck extends Truck implements Kitchen {
Kitchen kitchen;
public void cook(Food foodItem) {
kitchen.cook(foodItem);
}
}
He is a happy man because he can now do things like ;
pizzaTruck.driveTo(beach);
pizzaTruck.cook(pizzaWithExtraAnchovies);
Ok, this silly story was to make the point that it is no simulation of multiple inheritance, it is real multiple inheritance with the proviso that you can only inherit the contract, only inherit from empty abstract base classes which are called interfaces.
(update: with the coming of default methods interfaces now can also provide some behavior to be inherited)
You're probably confused because you view multiple inheritance locally, in terms of one class inheriting implementation details from multiple parents. This is not possible in Java (and often leads to abuse in languages where it's possible).
Interfaces allow multiple inheritance of types, e.g. a class Waterfowl extends Bird implements Swimmer can be used by other classes as if it were a Bird and as if it were a Swimmer. This is the the deeper meaning of multiple inheritance: allowing one object to act like it belongs to several unrelated different classes at once.
Here is a way to achieve multiple inheritance through interfaces in java.
What to achieve?
class A extends B, C // this is not possible in java directly but can be achieved indirectly.
class B{
public void getValueB(){}
}
class C{
public void getValueC(){}
}
interface cInterface{
public getValueC();
}
class cChild extends C implemets cInterface{
public getValueC(){
// implementation goes here, call the super class's getValueC();
}
}
// Below code is **like** class A extends B, C
class A extends B implements cInterface{
cInterface child = new cChild();
child.getValueC();
}
given the two interfaces below...
interface I1 {
abstract void test(int i);
}
interface I2 {
abstract void test(String s);
}
We can implement both of these using the code below...
public class MultInterfaces implements I1, I2 {
public void test(int i) {
System.out.println("In MultInterfaces.I1.test");
}
public void test(String s) {
System.out.println("In MultInterfaces.I2.test");
}
public static void main(String[] a) {
MultInterfaces t = new MultInterfaces();
t.test(42);
t.test("Hello");
}
}
We CANNOT extend two objects, but we can implement two interfaces.
Interfaces don't simulate multiple inheritance. Java creators considered multiple inheritance wrong, so there is no such thing in Java.
If you want to combine the functionality of two classes into one - use object composition. I.e.
public class Main {
private Component1 component1 = new Component1();
private Component2 component2 = new Component2();
}
And if you want to expose certain methods, define them and let them delegate the call to the corresponding controller.
Here interfaces may come handy - if Component1 implements interface Interface1 and Component2 implements Interface2, you can define
class Main implements Interface1, Interface2
So that you can use objects interchangeably where the context allows it.
It's pretty simple. You can implement more than one interface in a type. So for example, you could have an implementation of List that is also an instance of Deque (and Java does...LinkedList).
You just can't inherit implementations from multiple parents (i.e. extend multiple classes). Declarations (method signatures) are no problem.
You know what, coming from the perspective of a JavaScript dev trying to understand what the heck is going on with this stuff, I'd like to point out a couple things and somebody please tell me what I'm missing here if I'm way off the mark.
Interfaces are really simple. Stupidly, insanely simple. They're as stupidly, insanely simple as people initially think, which is why there are so many duplicate questions on this exact subject because the one reason to use them has been made unclear by people trying to make more of them than they are and there is widespread misuse in every Java server-side code-base I've ever been exposed to.
So, why would you want to use them? Most of the time you wouldn't. You certainly wouldn't want to use them ALL the time as many seem to think. But before I get to when you would, let's talk about what they're NOT.
Interfaces are NOT:
in any way a workaround for any sort of inheritance mechanism that Java lacks. They have nothing to do with inheritance, they never did, and in no way simulate anything inheritance-like.
necessarily something that helps you with stuff you wrote, so much as it helps the other guy write something meant to be interfaced by your stuff.
They really are as simple as you think they are on first glance. People misuse stupidly all the time so it's hard to understand what the point is. It's just validation/testing. Once you've written something conforms to an interface and works, removing that "implements" code won't break anything.
But if you're using interfaces correctly, you wouldn't want to remove it because having it there gives the next developer a tool for writing an access layer for another set of databases or web services that they want the rest of your app to continue using because they know their class will fail until they get the 100% complete-as-expected-interface in place. All interfaces do is validate your class and establish that you have in fact implemented an interface as you promised you would. Nothing more.
They're also portable. By exposing your interface definitions you can give people wanting to use your unexposed code a set of methods to conform to in order for their objects to use it correctly. They don't have to implement the interfaces. They could just jot them down on a piece of notepad paper and double-check that. But with the interface you have more of a guarantee nothing is going to try to work until it has a proper version of the interface in question.
So, any interface not likely to ever be implemented more than once? Completely useless. Multiple-inheritance? Stop reaching for that rainbow. Java avoids them for a reason in the first place and composited/aggregate objects are more flexible in a lot of ways anyway. That's not to say interfaces can't help you model in ways that multiple-inheritance allows but it's really not inheritance in any way shape or form and shouldn't be seen as such. It's just guaranteeing that your code won't work until you've implemented all of the methods you established that you would.
It's not a simulation of multiple inheritance. In java you can't inherit from two classes, but if you implements two interfaces "it seems like you inherited from two different classes" because you can use your class as any of your two intefaces.
For example
interface MyFirstInteface{
void method1();
}
interface MySecondInteface{
void method2();
}
class MyClass implements MyFirstInteface, MySecondInteface{
public void method1(){
//Method 1
}
public void method2(){
//Method 2
}
public static void main(String... args){
MyFirstInterface mfi = new MyClass();
MySecondInterface msi = new MyClass();
}
}
This will work and you can use mfi and msi, it seems like a multi inheritance, but it's not because you don't inherit anything, you just rewrite public methods provided by the interfaces.
You need to be precise:
Java allows multiple inheritance of interface, but only single inheritance of implementation.
You do multiple inheritance of interface in Java like this:
public interface Foo
{
String getX();
}
public interface Bar
{
String getY();
}
public class MultipleInterfaces implements Foo, Bar
{
private Foo foo;
private Bar bar;
public MultipleInterfaces(Foo foo, Bar bar)
{
this.foo = foo;
this.bar = bar;
}
public String getX() { return this.foo.getX(); }
public String getY() { return this.bar.getY(); }
}
Just by the way, the reason why Java does not implement full multiple inheritance is because it creates ambiguities. Suppose you could say "A extends B, C", and then both B and C have a function "void f(int)". Which implementation does A inherit? With Java's approach, you can implement any number of interfaces, but interfaces only declare a signature. So if two interfaces include functions with the same signature, fine, your class must implement a function with that signature. If interfaces you inherit have functions with different signatures, then the functions have nothing to do with each other, so there is no question of a conflict.
I'm not saying this is the only way. C++ implements true multiple inheritance by establishing precedence rules of which implementation wins. But the authors of Java decided to eliminate the ambiguity. Whether because of a philosophical belief that this made for cleaner code, or because they didn't want to do all the extra work, I don't know.
It's not fair to say that interfaces 'simulate' multiple inheritance.
Sure, your type can implement multiple interfaces and act as many different types polymorphically. However, you obviously won't inherit behaviour or implementations under this arrangement.
Generally look at composition where you think you may need multiple inheritance.
OR A potential solution to achieving something multiple inheritance like is the Mixin interface - http://csis.pace.edu/~bergin/patterns/multipleinheritance.html. Use with care!
They don't.
I think that the confusion comes from people believing that implementing an interface constitutes some form of inheritance. It doesn't; the implementation can simply be blank, no behavior is forced by the act or guaranteed through any contract. A typical example is the Clonable-interface, which while alluding to lots of great functionality, which defines so little that's it's essentially useless and potentially dangerous.
What do you inherit by implementing an interface? Bubkes! So in my opinion, stop using the words interface and inheritance in the same sentence. As Michael Borgwardt said, an interface is not a definition but an aspect.
You can actually "inherit" from multiple concrete classes if they implement interfaces themselves. innerclasses help you achieve that:
interface IBird {
public void layEgg();
}
interface IMammal {
public void giveMilk();
}
class Bird implements IBird{
public void layEgg() {
System.out.println("Laying eggs...");
}
}
class Mammal implements IMammal {
public void giveMilk() {
System.out.println("Giving milk...");
}
}
class Platypus implements IMammal, IBird {
private class LayingEggAnimal extends Bird {}
private class GivingMilkAnimal extends Mammal {}
private LayingEggAnimal layingEggAnimal = new LayingEggAnimal();
private GivingMilkAnimal givingMilkAnimal = new GivingMilkAnimal();
#Override
public void layEgg() {
layingEggAnimal.layEgg();
}
#Override
public void giveMilk() {
givingMilkAnimal.giveMilk();
}
}
I'd like to point out something that bit me in the behind, coming from C++ where you can easily inherit many implementations too.
Having a "wide" interface with many methods means that you'll have to implement a lot of methods in your concrete classes and you can't share these easily across implementations.
For instance:
interface Herbivore {
void munch(Vegetable v);
};
interface Carnivore {
void devour(Prey p);
}
interface AllEater : public Herbivore, Carnivore { };
class Fox implements AllEater {
...
};
class Bear implements AllEater {
...
};
In this example, Fox and Bear cannot share a common base implementation for both it's interface methods munch and devour.
If the base implementations look like this, we'd maybe want to use them for Fox and Bear:
class ForestHerbivore implements Herbivore
void munch(Vegetable v) { ... }
};
class ForestCarnivore implements Carnivore
void devour(Prey p) { ... }
};
But we can't inherit both of these. The base implementations need to be member variables in the class and methods defined can forward to that. I.e:
class Fox implements AllEater {
private ForestHerbivore m_herbivore;
private ForestCarnivore m_carnivore;
void munch(Vegetable v) { m_herbivore.munch(v); }
void devour(Prey p) { m_carnivore.devour(p); }
}
This gets unwieldy if interfaces grow (i.e. more than 5-10 methods...)
A better approach is to define an interface as an aggregation of interfaces:
interface AllEater {
Herbivore asHerbivore();
Carnivore asCarnivore();
}
This means that Fox and Bear only has to implement these two methods, and the interfaces and base classes can grow independetly of the aggregate AllEater interface that concerns the implementing classes.
Less coupling this way, if it works for your app.
I don't think they do.
Inheritance is specifically an implementation-oriented relationship between implementations. Interfaces do not provide any implementation information at all, but instead define a type. To have inheritance, you need to specifically inherit some behaviors or attributes from a parent class.
I believe there is a question here somewhere specifically about the role of interfaces and multiple inheritance, but I can't find it now...
There's really no simulation of multiple inheritance in Java.
People will sometimes say that you can simulate multiple inheritance using Interfaces because you can implement more than one interface per class, and then use composition (rather than inheritance) in your class to achieve the behaviors of the multiple classes that you were trying to inherit from to begin with.
If it makes sense in your object model, you can of course inherit from one class and implement 1 or more interfaces as well.
There are cases where multiple-inheritance turns to be very handy and difficult to replace with interfaces without writing more code. For example, there are Android apps that use classes derived from Activity and others from FragmentActivity in the same app. If you have a particular feature you want to share in a common class, in Java you will have to duplicate code instead of let child classes of Activity and FragmentsActivity derive from the same SharedFeature class. And the poor implementation of generics in Java doesn't help either because writing the following is illegal:
public class SharedFeature<T> extends <T extends Activity>
...
...
There is no support for multiple inheritance in java.
This story of supporting multiple inheritance using interface is what we developers cooked up. Interface gives flexibility than concrete classes and we have option to implement multiple interface using single class. This is by agreement we are adhering to two blueprints to create a class.
This is trying to get closer to multiple inheritance. What we do is implement multiple interface, here we are not extending (inheriting) anything. The implementing class is the one that is going to add the properties and behavior. It is not getting the implementation free from the parent classes. I would simply say, there is no support for multiple inheritance in java.
No, Java does not support multiple inheritance.
Neither using class nor using interface. Refer to this link for more info
https://devsuyed.wordpress.com/2016/07/21/does-java-support-multiple-inheritance
I also have to say that Java doesn't support multiple inheritance.
You have to differentiate the meaning between extends and implements keywords in Java. If we use extends, we are actually inheriting the class after that keyword. But, in order to make everything simple, we can't use extends more than once. But you can implement as many Interfaces as you wish.
If you implement an interface, there's a zero chance that you will miss the implementation of all the methods in each interface (Exception: default implementations of interface methods introduced in Java 8) So, you are now fully aware of what is happening with the things that you have embedded to your fresh class.
Why Java doesn't allow multiple inheritance is actually, multiple inheritance makes the code somewhat complex. Sometimes, two methods of parent classes might conflict due to having the same signatures. But if you are forced to implement all the methods manually, you will get the full understanding about what's going on, as I mentioned above. It makes your code more understandable to you.
If you need more info on Java interfaces, check out this article, http://www.geek-programmer.com/introduction-to-java-interfaces/
Between two Java class multiple Inheritance directly is not possible. In this case java recommend Use to interface and declare method inside interface and implement method with Child class.
interface ParentOne{
public String parentOneFunction();
}
interface ParentTwo{
public String parentTwoFunction();
}
class Child implements ParentOne,ParentTwo{
#Override
public String parentOneFunction() {
return "Parent One Finction";
}
#Override
public String parentTwoFunction() {
return "Parent Two Function";
}
public String childFunction(){
return "Child Function";
}
}
public class MultipleInheritanceClass {
public static void main(String[] args) {
Child ch = new Child();
System.out.println(ch.parentOneFunction());
System.out.println(ch.parentTwoFunction());
System.out.println(ch.childFunction());
}
}

Confusion in regarding implementing interface methods

HI
I have a question If interface has got four methods,and I like to implement only two methods, how this could be achieved?
Can any explain is that possible or should I go for implementing all the methods.
You can't "partially" implement an interface without declaring the implementing class abstract, thereby requiring that some subclass provide the remaining implementation. The reason for this is that an interface is a contract, and implementing it declares "I provide the behavior specified by the interface". Some other code is going to use your class via the declared interface and will expect the methods to be there.
If you know the use case does not use the other two methods you can implement them by throwing OperationNotSupported. Whether this is valid or not very much depends on the interface and the user. If the interface can legitimately be partially implemented this way it would be a code smell that the interface is poorly designed and perhaps should have been two interfaces.
You may also be able "implement" the interface by doing nothing, though this is usually only proper for "listener" or "callback" implementations.
In short, it all depends.
If you control the design of the interface, simply split it in two. One interface specifies the two only some implementations implement, and one interface specifies the other two (or inherits the first two and adds more, your choice)
You can make the implementing class abstract and implement two of the 4 methods from the interface.
I think #sateesh 's answer is the one closer to solving your problem. Let me elaborate on it. First of all, it is imperative that any class implementing an interface should provide definitions for all of its methods. But in some cases the user may find no use for a majority of the methods in the interface save for one or two. Consider the following interface having 6 abstract methods:
public interface HugeInterface {
void a();
void b();
void c();
void d();
void e();
void f();
}
Suppose your code finds use for the method 'c()' only and you wish to provide implementation details for only the method 'c()'. You can create a new class HugeInterfaceAdapter in a separate file which implements all the methods of the interface HugeInterface like shown below:
public class HugeInterfaceAdapter implements HugeInterface {
public void a() {}
public void b() {}
public void c() {}
public void d() {}
public void e() {}
public void f() {}
}
Note that you need not provide any actual implementation code for any of the methods. Now comes the interesting part. Yes, your class in which the need to implement a huge interface arose in the first place.
public class MyClass {
HugeInterfaceAdapter mySmallInterface = new HugeInterfaceAdapter() {
#Override
public void c() {
//Your class-specific interface implementation code here.
}
};
}
Now you can use the reference variable mySmallInterface in all the places where a HugeInterface is expected. This may seem a little hackish but I may say that it is endorsed officially by Java and classes like MouseAdapter bears testimony to this fact.
It's not possible.
You can implement all four methods, but the two you don't need should throw an UnsupportedOperationException.
If you want a concrete class which is implementing this interface, then it is not possible to have unimplemented methods, but if you make have abstract class implementing this interface then you can leave any number of methods as you want to be unimplemented.
As other answers mention you cannot have a concrete class implementing only some of the methods of the interface it implements. If you have no control over the interface your class is extending, you can think of having Adapter classes.
The abstract Adapter class can provide dummy implementation for the methods of an interface and the client classes can
extend the Adapter class. (Of course the disadvantage is that you cannot extend more than one class)
This is common practice with GUI programming (using Swing) where the event listener class
might not be interested in implementing all methods specified by the EventListener interface. For example
take a look at the java.awt.event.MouseListener interface and and the corresponding adapter class java.awt.event.MouseAdapter.

Categories