This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 7 years ago.
I have an abstract class Employee that implements interface IEmployee and is further composed of abstract classes like EmploymentType. I have used Abstract classes, so as to avoid code duplication for common functionality among sub classes.
So I want to ask following questions:
Does moving abstract methods from abstract classes to interfaces will improve the design?
Secondly, Are Interfaces better than Abstract classes for big projects? The reason why I am asking this is because I have seen a lot of enterprise applications where interfaces are used a lot more than abstract classes. Which gives an impression that using interfaces is the right way to build enterprise applications.
What common logic exists in your base abstract Employee class? I'd say any shared logic is probably trivial and probably could just be copied among the descendents (DRY isn't always necessarily the way to go). That way, you can just have an Employee interface, and one or more direct concrete ancestors, with some duplicated code in the constructors, getters and setters. It's arguably controversial but I've seen this approach preferred over and over.
EmploymentType and WorkLocation could be enums instead of classes, to avoid the arbitrary String fields. Perhaps WorkTime could also be an enum; I can't see it's structure in your UML. The hourlyPay field could be encapsulated in one of the enum types; I'm not sure where it best belongs with the information you've given.
On your general question about interfaces, see Effective Java by Joshua Bloch, Item 18 ("prefer interfaces to abstract classes"). Also the item "prefer composition to inheritance". Interfaces are simpler and more flexible from a design standpoint, and are particularly preferred for their testability. This is because if you have collaborators which are declared as instances of abstract classes, then they may contain logic which is hard to test (e.g. initialisation or additional dependencies). Collaborators declared as an interface type can be mocked 100%.
Related
This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 8 years ago.
I haven't done OOP in a while so I'm a bit rusty.
For an example, i have a client with a rental subscription, and it exist 3 type of subscription. How can i choose between abstract class and interface for my "Subscription" class?
Each subscription must have the price, maximum Rental Duration and maximum Rental Count.
From what I remember, I would use interface here but how can I force other classes that implements subscription to specify the value(constant) of these 3 properties?
If you're thinking of defining fields that are common to all implementations, you can't use an interface, because an interface does not contain state. It can just declare methods and constants. State is considered part of an implementation, not type information.
You could, however, define three abstract getter methods - getPrice(), getDuration() and getCount() or something like that, and leave the actual implementation of how those work to the implementing classes. In that case, you could use either an interface or an abstract class.
You'd choose an abstract class if you have some implementation that you want to have which is common to all subclasses. For example, if you have a specific way to perform "rent out", or "send reminder to renter" or other operations. Those methods will be concrete, and only the above three getters will be abstract.
If you don't have any common operations, and you find yourself just having the abstract methods and nothing else, an interface will probably serve you best, especially so because Java is single-inheritance, and using an interface will allow you to extend another class when you are creating your concrete classes.
These are just rules of thumb, though, not rules set in stone.
I think an abstract class makes more sense in this case. Use abstract classes when your classes all deal with the same data/methods but may slightly differ in method logic.
Interfaces may be more useful when you have several classes which have large differences but should always be constrained to a set of methods(the interface methods)
In general you use abstraction in case of inheritance and polymorphism. When you have an object that can have different behavior based on its internal type. Interfaces are used when there is a need for a contract. In general abstraction is best for objects that are closely related, while interfaces are chosen for their functionality.
In your case abstraction makes sense. You can keep the mutual properties in your base class and derive other classes from it. Eliminates some redundant code.
Here is what MS suggested:Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
*If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
*If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
*If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
*If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
https://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
C++ promotes a separation between class definitions and class implementations but not JAVA
I want to know why does JAVA does not do like in C++ and promotes the separation between class definitions and class implementations. Are there any advantages with that way of working or proceding for a mather of code reuse of extensibility?
Moved to https://softwareengineering.stackexchange.com/questions/118574/c-promotes-a-separation-between-class-definitions-and-class-implementations-bu
Java does offer the ability to separate type definitions from their implementations. Use an interface to define the type and a class implementing that interface for the implementation.
Java supports separate definition of interfaces and classes.
You can have the same kind of separation between definition and implementation in Java. We do it all the time in our development work through Interface Driven Design. We design the entire system as a set of interfaces that represent behavior and functionality in the system. Once the interfaces are defined, we create implementing classes that realize the behavior defined by the interfaces.
This gives us the ability to refer to our components by there interfaces and the flexibility to replace particular implementations without having to modify the references throughout the code base.
The one caveat about such a design method is the need to do dependency injection to maintain the separation between types. The dependency injection can be done either manually, or, as most people do it, using a DI framework such as the one included in Spring.
Java's creators encourage coding by interface (known as design by contract). An interface is somehow similar to an abstract class in C++, with the following enforcement : all declared methods are abstract and public, no class variables are allowed, constants must are public.
This question already has answers here:
Abstract class vs Interface in Java
(15 answers)
Closed 5 years ago.
In interview I have been asked following question. I tried to answer the question but I want exact answer of the question.
If I can simulate Abstract class as Interface, why java provided Interface?
This mean if in Abstract class I can mark all methods as abstract and then abstract class will work as interface, so why I need interface.
Can anyone explain me in brief.
That's a very standard interview question. The answer is: because you can implement multiple interfaces, but can't extend multiple abstract classes.
Example from the JRE: LinkedList is both a List and a Deque. These interfaces define the behaviour of the class. They do not provide any implementation details. While abstract classes could provide some.
Related questions: this and this. The latter is not directly related, but it shows why are interfaces needed, even in cases when an abstract class would suffice.
Interfaces define contracts & can define constants, but provide no implementation at all of the contracted methods.
Abstract classes can provide implementations of methods as well as member variables - if you want you can create an abstract class that defines everything except the fine-tuning you want in your concrete subclasses. You can't do this with interfaces, but you can implement multiple interfaces & extend only one parent class.
Both interfaces & abstract classes can be used to make use of concrete classes polymorphically.
Abstract classes do well to set default methods and set up the hierarchy. The issue is subclasses may only extend a superclass one-time. Interfaces on the other hand can extend each other multiple times and subclasses can implement any number of interfaces. This provides a lot of flexibility and affords the potential for change. Ideally, the can be combined i.e. abstract class implements interface1…interface2, best of both worlds.
The reason why interviewers ask this question is because your answer reflects your deep understanding of what a programming language (and a compiler) is. In particular, Java defines the concept of interface on top of (pure) abstract classes in order to (partially) support multiple inheritance (between interfaces). If this mechanism had not been introduced, we would have either no way of achieving some sort of multiple inheritance, or the big mess created by fully-fledged multiple inheritance in C++.
Answer
1) MULTIPLE INHERITANCE in java is achieved through interfaces.
2) If there is a situation where some explanation of a method is required, but not a full fledged one, the best way is to use abstract class.
3)Interfaces merely provide an AGREEMENT for the return type and the argument types.
This question already has answers here:
Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?
(21 answers)
Closed 9 years ago.
I can make abstract class equivalent to interface by putting all abstract methods within abstract class. Why did Java's designers choose to provide support for interfaces and single inheritance instead of multiple inheritance and abstract classes. What is the advantage?
At least for one reason (besides the conceptual differences between the two): you can implement multiple interfaces but you can only inherit from a single abstract class at most.
Class-based multiple inheritance is not supported by Java. You can only inherit from a single class, but you can implement multiple interfaces.
This becomes handy when you need to treat multiple classes polymorphicly when they have different inheritance trees.
An interface is a contract between a class and its behavior. If a class implements an interface, it MUST provide implementation for the methods specified in the interface. There's a number of things that differentiate the two, however.
Check out the Oracle website for more on the differences between interfaces and abstract classes:
http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
If you have multiple classes and you want to force that there would be some methods that should be common among them, irrespective of their behavior(implementation), Interface does that for you
Interface, is like a contract, which every other class which implements it has to follow
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why there is no multiple inheritance in Java, but implementing multiple interfaces is allowed
Why Java allows multiple inheritance from interfaces but not from abstract or concrete classes
Multiple inheritance of concrete classes raises a variety of issues.
For example, what if a class inherits two different implementations of the same method from two different base classes?
To avoid these issues, Java doesn't support this feature.
Unlike concrete classes, interfaces cannot have method bodies.
Therefore, none of these issues apply to interfaces.
Because implementing an interface is not inheritance. It simply means that your class will adhere to a predefined contract, typically to provide a set of methods related to a certain functionality. Any class can adhere to many such contracts without conflict (unless two of those interfaces define the same method).
Unlike inheritance, it does not automagically receive attributes or functionality due to a hierarchical relationship with its superclass since no such relationship exists.
Multiple inheritance is basically not allowed in Java or many other OO languages due to the already mentioned Diamond Inheritance problem.
I really don't like the term "inherit" here, it leads to a lot of confusion.
Java only allows interfaces to extend other interfaces, and for classes to implement interfaces.
If you look at an interface as a mathematical set of declarations, then each "extends" merely provides the union of the set from the superinterface and that of the current interface. You are therefore allowed to do multiple "unions".
When you eventually get to a class that implements one or more interfaces, the semantics here are merely that the class must provide implementations for all the methods in the set. A class implementing multiple interfaces could be rewritten as a class implementing a single interface that extends all the above interfaces.
In the case of classes inheriting multiple classes it is not allowed because it leads to a variety of problems, including the diamond problem. For instance, if I have two supertypes with different implementations of the same method signature, which one should be used in the subtype?
To make language simpler and more elegant. C++ allows a lots of stuff, but it's often pain to learn and use. We (me, at least :)) don't want java to be like that.