I have the following situation:
I need my class let's say A to extend JComponent and a different class let's say B.
Now, I know that multiple inheritance is not possible in java, and that a proper way to do this would be to implement BInterface which will give me access to all methods from B.
The issue is that class B contains ~15 methods, and inside A I only need to override 2 of them, and all the other ones to use the 'super' implementation.
Question is: is there a possible way to do this without having to implement inside A all the methods from B?
Note: I'm not trying to add too much complexity to my code, if the 'workaround' for this problem breaks oop programming principles then I should better redesign my code.
As you said multiple inheritance is not supported in java. But in general its a good practice to use composition instead of inheritance [Effective Java - item 18]. Read about it here
You can use default implementation of java 8 feature.
Create an interface named as ABinterface. provide all 13 methods as default means
having definition and declare 2 methods (like abstract methods).
Class A and B will implement ABinterface and override those 2 methods according to
their need.
Class A which will extend jsComponent and implement ABInterface can access all
other existing 13 methods also.
You haven't provided the enough information in this query. So you need to think according
to real word scenarios with oops concepts before implementing this.
You can also use composition instead of inheritance.
Related
I know this question has been asked many times and we have articles all over the internet but I still cannot fully understand, when should I use interface or abstract class since I am using Java 15.
Most of the articles talk about the differences and use cases before Java 8 which makes sense but not when you can basically provide body for your methods in interface.
The only thing that made sense to me is non-public and non-final restrictions.
I would really appreciate if somebody can point out 1-2 examples of the scenarios where I need to choose between interface and abstract class in Java 15. Also, would be great if it can be in terms of real life projects rather than Animal or shape class examples.
Thanks !!
default methods on interface
Apparently you are referring to the feature of “default methods” implementing behavior in an interface.
You should understand that the feature was added as a way around this dilemma: How to retroactively add features leveraging streams and lambda on existing interfaces without breaking existing classes that implement those interfaces?
Many new methods were added to those interfaces such as in the Java Collections Framework. Adding methods to an existing interface would automatically break all classes implementing the interface that are lacking the newly-required methods. Being able to provide a fallback, to give an implementation where one is now required but not yet existing, would resolve the dilemma. Thus « default methods » were born.
To quote from the Oracle tutorial linked above:
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
To quote this Answer by Brian Goetz, Java Language Architect at Oracle:
The proximate reason for adding default methods to interfaces was to support interface evolution
So this feature of adding default behavior to an interface was not meant to be a new mainstream feature in and of itself. The intent of default was not to replace abstract.
Indeed, some experienced Java experts have recommended against making a habit of writing default methods on an interface. They recommend pretty much ignoring that feature of the Java language. Continue to think of interfaces as simply defining a contract, and abstract classes as providing partial implementations meant to be completed in a subclass.
You are certainly free to write your own default methods on your interfaces. And certainly you should do so if you are in a similar situation of having published an interface that others may have implemented, and now you want to add methods. But unnecessarily adding default methods is likely to confuse other programmers who expect partial implementations on an abstract class rather than an interface.
Four situations calling for default method on an interface
In that same post linked above, Brian Goetz suggests three other cases beyond interface evolution where default methods on an interface may be appropriate. Here is a quick mention; see his post for details.
Optional methods - The default method throws an UnsupportedOperationException because we expect implementations of this interface to more often not want to implement this method.
Convenience methods
Combinators
Start with interface, move to abstract class for shared code
As for choosing between an interface and abstract class:
Generally start with an interface. Or several interfaces if you want various implementing classes to mix various contracts (see mixin).
Think twice before adding a default method. Consider if your situation meets one of the four cases recommended by Brian Goetz as discussed above.
If you come to realize that you have duplicated code across multiple classes, then consider centralizing that shared code to an abstract class to be used across subclasses.
Alternatively, use composition rather than inheritance (discussed below).
For example, you might have a class for domestic ShippingLabelUS as well as ShippingLabelCanada and ShippingLabelOverseas. All three need to convert between imperial pounds and metric kilograms. You find yourself copying that code between the classes. At this point you might consider having all three classes extend from abstract class ShippingLabel where a single copy of the weight conversion methods live.
While designing your API keep in mind that Java, like most OOP languages, has single-inheritance. So your subclasses are limited to extending only one class. To be a bit more specific about the single-versus-multiple inheritance, I will quote Brian Goetz from this PDF of a slide deck:
[regarding default methods on an interface]
Wait,is this multiple inheritance in Java?
• Java always had multiple inheritance of types
• This adds multiple inheritance of behavior
• But not of state, where most of the trouble comes from
Composition over inheritance
An alternative to using an abstract class for shared behavior is creating a separate class for specific behavior, then adding an object of that separate class to be kept as a member field on the larger class. Wise programmers often share this pearl of wisdom: Prefer composition over inheritance.
Regarding the shipping label example above, you could create a WeightConverter class, an object of which would be a member of each of the three label classes. In this arrangement, no need for the abstract class.
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.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why does Java allow multiple inheritance from interfaces but not from abstract/concrete classes
Why there is no multiple inheritance in Java, but implementing multiple interfaces is allowed
Instead of inheriting from multiple classes (which Java doesn't allow), why are we told to implement multiple interfaces instead?
Surely the point of inheriting from multiple classes is the inherit their functionality - if you have to manually re-insert functionality (for each class extending a set of interfaces) what's the point of using the interfaces? There's no guarantee that two classes implementing the same set of interfaces will provide the same functionality - or am I missing something?
Multiple inheritance is something that can cause multiple problems.
Interfaces are used to give abilities to instances of the class that implement them. I personally use interfaces with composition(using instance variables that are references to other objects) in order to provide functionality to my class that would otherwise be achieved with multiple inheritance.
In other words my class provides the functionality promised by the interface implemented but internally my class instance uses the instance variable to do the job.
"There's no guarantee that two classes
implementing the same set of
interfaces will provide the same
functionality - or am I missing
something?"
About your statement above:
Each method should adhere to a contract so no matter how you implement it the functionality of the method should always be the same if this is what is supposed to do. If it breaks the contract it means it was implemented wrongly.
multiple inheritance may lead to cyclic inheritance.. to avoid that we are going for interface based inheritance..
You should read about the diamond dependency problem http://en.wikipedia.org/wiki/Diamond_problem and to avoid this Java chose interfaces over extension of multiple classes
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.
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...