Related
I was asked a question, I wanted to get my answer reviewed here.
Q: In which scenario it is more appropriate to extend an abstract class rather than implementing the interface(s)?
A: If we are using template method design pattern.
Am I correct ?
I am sorry if I was not able to state the question clearly.
I know the basic difference between abstract class and interface.
1) use abstract class when the requirement is such that we need to implement the same functionality in every subclass for a specific operation (implement the method) and different functionality for some other operations (only method signatures)
2) use interface if you need to put the signature to be same (and implementation different) so that you can comply with interface implementation
3) we can extend max of one abstract class, but can implement more than one interface
Reiterating the question: Are there any other scenarios, besides those mentioned above, where specifically we require to use abstract class (one is see is template method design pattern is conceptually based on this only)?
Interface vs. Abstract class
Choosing between these two really depends on what you want to do, but luckily for us, Erich Gamma can help us a bit.
As always there is a trade-off, an interface gives you freedom with regard to the base class, an abstract class gives you the freedom to add new methods later. – Erich Gamma
You can’t go and change an Interface without having to change a lot of other things in your code, so the only way to avoid this would be to create a whole new Interface, which might not always be a good thing.
Abstract classes should primarily be used for objects that are closely related. Interfaces are better at providing common functionality for unrelated classes.
When To Use Interfaces
An interface allows somebody to start from scratch to implement your interface or implement your interface in some other code whose original or primary purpose was quite different from your interface. To them, your interface is only incidental, something that have to add on to the their code to be able to use your package. The disadvantage is every method in the interface must be public. You might not want to expose everything.
When To Use Abstract classes
An abstract class, in contrast, provides more structure. It usually defines some default implementations and provides some tools useful for a full implementation. The catch is, code using it must use your class as the base. That may be highly inconvenient if the other programmers wanting to use your package have already developed their own class hierarchy independently. In Java, a class can inherit from only one base class.
When to Use Both
You can offer the best of both worlds, an interface and an abstract class. Implementors can ignore your abstract class if they choose. The only drawback of doing that is calling methods via their interface name is slightly slower than calling them via their abstract class name.
reiterating the question: there is any other scenario besides these
mentioned above where specifically we require to use abstract class
(one is see is template method design pattern is conceptually based on
this only)
Yes, if you use JAXB. It does not like interfaces. You should either use abstract classes or work around this limitation with generics.
From a personal blog post:
Interface:
A class can implement multiple interfaces
An interface cannot provide any code at all
An interface can only define public static final constants
An interface cannot define instance variables
Adding a new method has ripple effects on implementing classes (design maintenance)
JAXB cannot deal with interfaces
An interface cannot extends or implement an abstract class
All interface methods are public
In general, interfaces should be used to define contracts (what is to be achieved, not how to achieve it).
Abstract Class:
A class can extend at most one abstract class
An abstract class can contain code
An abstract class can define both static and instance constants (final)
An abstract class can define instance variables
Modification of existing abstract class code has ripple effects on extending classes (implementation maintenance)
Adding a new method to an abstract class has no ripple effect on extending classes
An abstract class can implement an interface
Abstract classes can implement private and protected methods
Abstract classes should be used for (partial) implementation. They can be a mean to restrain the way API contracts should be implemented.
Interface is used when you have scenario that all classes has same structure but totally have different functionality.
Abstract class is used when you have scenario that all classes has same structure but some same and some different functionality.
Take a look the article : http://shoaibmk.blogspot.com/2011/09/abstract-class-is-class-which-cannot-be.html
There are a lot of great answers here, but I often find using BOTH interfaces and abstract classes is the best route. Consider this contrived example:
You're a software developer at an investment bank, and need to build a system that places orders into a market. Your interface captures the most general idea of what a trading system does,
1) Trading system places orders
2) Trading system receives acknowledgements
and can be captured in an interface, ITradeSystem
public interface ITradeSystem{
public void placeOrder(IOrder order);
public void ackOrder(IOrder order);
}
Now engineers working at the sales desk and along other business lines can start to interface with your system to add order placement functionality to their existing apps. And you haven't even started building yet! This is the power of interfaces.
So you go ahead and build the system for stock traders; they've heard that your system has a feature to find cheap stocks and are very eager to try it out! You capture this behavior in a method called findGoodDeals(), but also realize there's a lot of messy stuff that's involved in connecting to the markets. For example, you have to open a SocketChannel,
public class StockTradeSystem implements ITradeSystem{
#Override
public void placeOrder(IOrder order);
getMarket().place(order);
#Override
public void ackOrder(IOrder order);
System.out.println("Order received" + order);
private void connectToMarket();
SocketChannel sock = Socket.open();
sock.bind(marketAddress);
<LOTS MORE MESSY CODE>
}
public void findGoodDeals();
deals = <apply magic wizardry>
System.out.println("The best stocks to buy are: " + deals);
}
The concrete implementations are going to have lots of these messy methods like connectToMarket(), but findGoodDeals() is all the traders actually care about.
Now here's where abstract classes come into play. Your boss informs you that currency traders also want to use your system. And looking at currency markets, you see the plumbing is nearly identical to stock markets. In fact, connectToMarket() can be reused verbatim to connect to foreign exchange markets. However, findGoodDeals() is a much different concept in the currency arena. So before you pass off the codebase to the foreign exchange wiz kid across the ocean, you first refactor into an abstract class, leaving findGoodDeals() unimplmented
public abstract class ABCTradeSystem implements ITradeSystem{
public abstract void findGoodDeals();
#Override
public void placeOrder(IOrder order);
getMarket().place(order);
#Override
public void ackOrder(IOrder order);
System.out.println("Order received" + order);
private void connectToMarket();
SocketChannel sock = Socket.open();
sock.bind(marketAddress);
<LOTS MORE MESSY CODE>
}
Your stock trading system implements findGoodDeals() as you've already defined,
public class StockTradeSystem extends ABCTradeSystem{
public void findGoodDeals();
deals = <apply magic wizardry>
System.out.println("The best stocks to buy are: " + deals);
}
but now the FX whiz kid can build her system by simply providing an implementation of findGoodDeals() for currencies; she doesn't have to reimplement socket connections or even the interface methods!
public class CurrencyTradeSystem extends ABCTradeSystem{
public void findGoodDeals();
ccys = <Genius stuff to find undervalued currencies>
System.out.println("The best FX spot rates are: " + ccys);
}
Programming to an interface is powerful, but similar applications often re-implement methods in nearly identical ways. Using an abstract class avoids reimplmentations, while preserving the power of the interface.
Note: one may wonder why findGreatDeals() isn't part of the interface. Remember, the interface defines the most general components of a trading system. Another engineer may develop a COMPLETELY DIFFERENT trading system, where they don't care about finding good deals. The interface guarantees that the sales desk can interface to their system as well, so it's preferable not to entangle your interface with application concepts like "great deals".
Which should you use, abstract classes or interfaces?
Consider using abstract classes if any of these statements apply to your use case:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your use case:
You expect that unrelated classes would implement your interface.
For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.
New methods added regularly to interface by providers, to avoid issues extend Abstract class instead of interface.
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
Things have been changed a lot in last three years with addition of new capabilities to interface with Java 8 release.
From oracle documentation page on interface:
An interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
As you quoted in your question, abstract class is best fit for template method pattern where you have to create skeleton. Interface cant be used here.
One more consideration to prefer abstract class over interface:
You don't have implementation in base class and only sub-classes have to define their own implementation. You need abstract class instead of interface since you want to share state with sub-classes.
Abstract class establishes "is a" relation between related classes and interface provides "has a" capability between unrelated classes.
Regarding second part of your question, which is valid for most of the programming languages including java prior to java-8 release
As always there is a trade-off, an interface gives you freedom with regard to the base class, an abstract class gives you the freedom to add new methods later. – Erich Gamma
You can’t go and change an Interface without having to change a lot of other things in your code
If you prefer abstract class to interface earlier with above two considerations, you have to re-think now as default methods have added powerful capabilities to interfaces.
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 select one of them between interface and abstract class, oracle documentation page quote that:
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.
Refer to these related questions fore more details:
Interface vs Abstract Class (general OO)
How should I have explained the difference between an Interface and an Abstract class?
In summary : The balance is tilting more towards interfaces now.
Are there any other scenarios, besides those mentioned above, where specifically we require to use abstract class (one is see is template method design pattern is conceptually based on this only)?
Some design patterns use abstract classes (over interfaces) apart from Template method pattern.
Creational patterns:
Abstract_factory_pattern
Structural patterns:
Decorator_pattern
Behavioral patterns:
Mediator_pattern
You are not correct. There are many scenarios. It just isn't possible to reduce it to a single 8-word rule.
The shortest answer is, extend abstract class when some of the functionalities uou seek are already implemented in it.
If you implement the interface you have to implement all the method. But for abstract class number of methods you need to implement might be fewer.
In template design pattern there must be a behavior defined. This behavior depends on other methods which are abstract. By making sub class and defining those methods you actually define the main behavior. The underlying behavior can not be in a interface as interface does not define anything, it just declares. So a template design pattern always comes with an abstract class. If you want to keep the flow of the behavior intact you must extend the abstract class but don't override the main behavior.
In my opinion, the basic difference is that an interface can't contain non-abstract methods while an abstract class can.
So if subclasses share a common behavior, this behavior can be implemented in the superclass and thus inherited in the subclasses
Also, I quoted the following from "software architecture design patterns in java" book
" In the Java programming language, there is no support for multiple inheritance.
That means a class can inherit only from one single class. Hence inheritance
should be used only when it is absolutely necessary. Whenever possible, methods
denoting the common behavior should be declared in the form of a Java interface to be implemented by different implementer classes. But interfaces suffer from the limitation that they cannot provide method implementations. This means that every implementer of an interface must explicitly implement all methods declared in an interface, even when some of these methods represent the invariable part of the functionality and have exactly the same implementation in all of the implementer classes. This leads to redundant code. The following example demonstrates how the Abstract Parent Class pattern can be used in such cases without requiring redundant method implementations."
Abstract classes are different from interfaces in two important aspects
they provide default implementation for chosen methods (that is covered by your answer)
abstract classes can have state (instance variables) - so this is one more situation you want to use them in place of interfaces
This is a good question The two of these are not similar but can be use for some of the same reason, like a rewrite. When creating it is best to use Interface. When it comes down to class, it is good for debugging.
This is my understanding, hope this helps
Abstract classes:
Can have member variables that are inherited (can’t be done in interfaces)
Can have constructors (interfaces can’t)
Its methods can have any visibility (ie: private, protected, etc - whereas all interface methods are public)
Can have defined methods (methods with an implementation)
Interfaces:
Can have variables, but they are all public static final variables
constant values that never change with a static scope
non static variables require an instance, and you can’t instantiate an interface
All methods are abstract (no code in abstract methods)
all code has to be actually written in the class that implements the particular interface
Usage of abstract and interface:
One has "Is-A-Relationship" and another one has "Has-A-Relationship"
The default properties has set in abstract and extra properties can be expressed through interface.
Example: --> In the human beings we have some default properties that are eating, sleeping etc. but if anyone has any other curricular activities like swimming, playing etc those could be expressed by Interface.
Abstract classes should be extended when you want to some common behavior to get extended. The Abstract super class will have the common behavior and will define abstract method/specific behavior which sub classes should implement.
Interfaces allows you to change the implementation anytime allowing the interface to be intact.
I think the answers here are missing the main point:
Java interfaces (the question is about Java but there are similar mechanisms in other languages) is a way to partially support multiple inheritance, i.e. method-only inheritance.
It is similar to PHP's traits or Python's duck typing.
Besides that, there is nothing additional that you truly need an interface for --and you cannot instantiate a Java interface.
I still have some confusion about this thing. What I have found till now is
(Similar questions have already been asked here but I was having some other points.)
Interface is collection of ONLY abstract methods and final fields.
There is no multiple inheritance in Java.
Interfaces can be used to achieve multiple inheritance in Java.
One Strong point of Inheritance is that We can use the code of base class in derived class without writing it again. May be this is the most important thing for inheritance to be there.
Now..
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Then why to make interfaces ?
NOTE : I have found one case in which interfaces are helpful. One example of it is like in Runnable interface we have public void run() method in which we define functionality of thread and there is built in coding that this method will be run as a separate thread. So we just need to code what to do in thread, Rest is pre-defined. But this thing also can be achieved using abstract classes and all.
Then what are the exact benefits of using interfaces? Is it really Multiple-Inheritance that we achieve using Interfaces?
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
We can't. Interfaces aren't used to achieve multiple inheritance. They replace it with safer, although slightly less powerful construct. Note the keyword implements rather than extends.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
They are not. With interfaces a single class can have several "views", different APIs or capabilities. E.g. A class can be Runnable and Callable at the same time, while both methods are effectively doing the same thing.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Interfaces are kind-of multiple inheritance with no problems that the latter introduces (like the Diamond problem).
There are few use-cases for interfaces:
Object effectively has two identities: a Tank is both a Vehicle and a Weapon. You can use an instance of Tank where either the former or the latter is expected (polymorphism). This is rarely a case in real-life and is actually a valid example where multiple inheritance would be better (or traits).
Simple responsibilities: an instance of Tank object in a game is also Runnable to let you execute it in a thread and an ActionListener to respond to mouse events.
Callback interfaces: if object implements given callback interface, it is being notified about its life-cycle or other events.
Marker interfaces: not adding any methods, but easily accessible via instanceof to discover object capabilities or wishes. Serializable and Cloneable are examples of this.
What you are looking for are trait (like in Scala), unfortunately unavailable in Java.
Interfaces are collection of final static fields and abstract methods (Newly Java 8 added support of having static methods in an interface).
Interfaces are made in situations when we know that some task must be done, but how it should be done can vary. In other words we can say we implement interfaces so that our class starts behaving in a particular way.
Let me explain with an example, we all know what animals are. Like Lion is an animal, monkey is an animal, elephant is an animal, cow is an animal and so on. Now we know all animals do eat something and sleep. But the way each animal can eat something or sleep may differ. Like Lion eats by hunting other animals where as cow eats grass. But both eat. So we can have some pseudo code like this,
interface Animal {
public void eat();
public void sleep();
}
class Lion implements Animal {
public void eat() {
// Lion's way to eat
}
public void sleep(){
// Lion's way to sleep
}
}
class Monkey implements Animal {
public void eat() {
// Monkey's way to eat
}
public void sleep() {
// Monkey's way to sleep
}
}
As per the pseudo code mentioned above, anything that is capable of eating or sleeping will be called an animal or we can say it is must for all animals to eat and sleep but the way to eat and sleep depends on the animal.
In case of interfaces we inherit only the behaviour, not the actual code as in case of classes' inheritance.
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Implementing interfaces is other kind of inheritance. It is not similar to the inheritance of classes as in that inheritance child class gets the real code to reuse from the base class.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
It is said because one class can implement more than one interfaces. But we need to understand that this inheritance is different than classes' inheritance.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Implementing an interface puts compulsion on the class that it must override its all abstract methods.
Read more in my book here and here
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Unfortunately, in colloquial usage, the word inheritance is still frequently used when a class implements an interface, although interface implementation would be a preferable term - IMO, the term inheritance should strictly be used with inheritance of a concrete or abstract class. In languages like C++ and C#, the same syntax (i.e. Subclass : Superclass and Class : Interface) is used for both class inheritance and interface implementation, which may have contributed to the spread of the misuse of the word inheritance with interfaces. Java has different syntax for extending a class as opposed to implementing an interface, which is a good thing.
Q2 If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
You can achieve the 'effect' of multiple inheritance through composition - by implementing multiple interfaces on a class, and then providing implementations for all methods, properties and events required of all the interfaces on the class. One common technique of doing this with concrete classes is by doing 'has-a' (composition) relationships with classes which implement the external interfaces by 'wiring up' the implementation to each of the internal class implementations. (Languages such as C++ do support multiple concrete inheritance directly, but which creates other potential issues like the diamond problem).
Q3 Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Interfaces allow existing classes (e.g. frameworks) to interact with your new classes without having ever 'seen' them before, because of the ability to communicate through a known interface. Think of an interface as a contract. By implementing this interface on a class, you are contractually bound to meet the obligations required of it, and once this contract is implemented, then your class should be able to be used interchangeably with any other code which consumes the interface.
Real World Example
A 'real world' example would be the legislation and convention (interface) surrounding an electrical wall socket in a particular country. Each electrical appliance plugged into the socket needs to meet the specifications (contract) that the authorities have defined for the socket, e.g. the positioning of the line, neutral and earth wires, the position and colouring of the on / off switch, and the conformance the the electrical voltage, frequency and maximum current that will be supplied through the interface when it is switched on.
The benefit of decoupling the interface (i.e. a standard wall socket) rather than just soldering wires together is that you can plug (and unplug) a fan, a kettle, a double-adapter, or some new appliance to be invented next year into it, even though this appliance didn't exist when the interface was designed. Why? Because it will conform to the requirements of the interface.
Why use interfaces?
Interfaces are great for loose coupling of classes, and are one of the mainstay's of Uncle Bob's SOLID paradigm, especially the Dependency Inversion Principle and Interface Segregation Principles.
Simply put, by ensuring that dependencies between classes are coupled only on interfaces (abstractions), and not on other concrete classes, it allows the dependency to be substituted with any other class implementation which meets the requirements of the interface.
In testing, stubs and mocks of dependencies can be used to unit test each class, and the interaction the class has with the dependency can be 'spyed' upon.
KISS
I have searched for days, nay weeks trying to understand interfaces and seem to read the same generic help; I'm not trying to disparage the contributions, but i think the light-bulb just clicked so I'm chuffed :))
I prefer to Keep It Simple Stupid, so will proffer my new found view of interfaces.
I'm a casual coder but i want to post this code i wrote in VB.NET (the principle is the same for other languages), to help others understand interfaces.
If i have it wrong, then please let others know in follow up comments.
Explanation
Three buttons on a form, clicking each one saves a different class reference to the interface variable (_data). The whole point of different class references into an interface variable, is what i didn't understand as it seemed redundant, then its power becomes evident with the msgbox, i only need to call the SAME method to perform the task i need, in this case 'GetData()', which uses the method in the class that's currently held by the interface reference variable (_data).
So however i wish to get my data (from a database, the web or a text file), it's only ever done using the same method name; the code behind that implementation...i don't care about.
It's then easy to change each class code using the interface without any dependency...this is a key goal in OO and encapsulation.
When to use
Code classes and if you notice the same verb used for methods, like 'GetData()', then it's a good candidate to implement an interface on that class and use that method name as an abstraction / interface.
I sincerely hope this helps a fellow noob with this difficult principle.
Public Class Form1
Private _data As IData = Nothing
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
_data = New DataText()
MsgBox(_data.GetData())
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
_data = New DataDB()
MsgBox(_data.GetData())
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
_data = New DataWeb()
MsgBox(_data.GetData())
End Sub
End Class
Public Interface IData
Function GetData() As String
End Interface
Friend Class DataText : Implements IData
Friend Function GetData() As String Implements IData.GetData
Return "DataText"
End Function
End Class
Friend Class DataDB : Implements IData
Friend Function GetData() As String Implements IData.GetData
Return "DataDB"
End Function
End Class
Friend Class DataWeb : Implements IData
Friend Function GetData() As String Implements IData.GetData
Return "DataWeb"
End Function
End Class
Old question. I'm suprised that nobody quoted the canonical sources: Java: an Overview by James Gosling, Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four or Effective Java by Joshua Bloch (among other sources).
I will start with a quote:
An interface is simply a specification of a set of methods that an object responds to. It does not include any instance variables or implementation. Interfaces can be multiply-inherited (unlike classes) and they can be used in a more flexible way than the usual rigid class
inheritance structure. (Gosling, p.8)
Now, let's take your assumptions and questions one by one (I'll voluntarily ignore the Java 8 features).
Assumptions
Interface is collection of ONLY abstract methods and final fields.
Did you see the keyword abstract in Java interfaces? No. Then you should not consider an interface as a collection of abstract methods. Maybe you are misleaded by the C++ so-called interfaces, which are classes with only pure virtual methods. C++, by design, does not have (and does not need to have) interfaces, because it has mutliple inheritance.
As explained by Gosling, you should rather consider an interface as "a set of methods that an object responds to". I like to see an interface and the associated documentation as a service contract. It describes what you can expect from an object that implements that interface. The documentation should specify the pre and post-conditions (e.g. the parameters should be not null, the output is always positive, ...) and the invariants (a method that does not modify the object internal state). This contract is the heart, I think, of OOP.
There is no multiple inheritance in Java.
Indeed.
JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. This primarily consists of operator overloading (although it does have method overloading), multiple inheritance, and extensive automatic coercions. (Gosling, p.2)
Nothing to add.
Interfaces can be used to achieve multiple inheritance in Java.
No, simlpy because there is no multiple inheritance in Java. See above.
One Strong point of Inheritance is that We can use the code of base class in derived class without writing it again. May be this is the most important thing for inheritance to be there.
That's called "implementation inheritance". As you wrote, it's a convenient way to reuse code.
But it has an important counterpart:
parent classes often define at least part of their subclasses' physical representation. Because inheritance exposes a subclass to details of its parent's implementation, it's often said that "inheritance breaks encapsulation" [Sny86]. The implementation of a subclass becomes so bound up with the implementation of its parent class that any change in the parent's implementation will force the subclass to change. (GOF, 1.6)
(There is a similar quote in Bloch, item 16.)
Actually, inheritance serves also another purpose:
Class inheritance combines interface inheritance and implementation inheritance. Interface inheritance defines a new interface in terms of one
or more existing interfaces. Implementation inheritance defines a new implementation in terms of one or more existing implementations. (GOF, Appendix A)
Both use the keyword extends in Java. You may have hierarchies of classes and hierarchies of interfaces. The first ones share implementation, the second ones share obligation.
Questions
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.**
Implementation of an interface is not inheritance. It's implementation. Thus the keyword implements.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?**
No multiple inheritance in Java. See above.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it./Then why to make interfaces ?/What are the exact benefits of using interfaces? Is it really Multiple-Inheritance that we achieve using Interfaces?
The most important question is: why would you like to have multiple-inheritance? I can think of two answers: 1. to give mutliple types to an object; 2. to reuse code.
Give mutliple types to an object
In OOP, one object may have different types. For instance in Java, an ArrayList<E> has the following types: Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess, AbstractList<E>, AbstractCollection<E> and Object (I hope I have not forgotten anyone). If an object has different types, various consumers will be able use it without be aware of its specificities. I need an Iterable<E> and you give me a ArrayList<E>? It's ok. But if I need now a List<E> and you give me a ArrayList<E>, it's ok too. Etc.
How do you type an object in OOP? You took the Runnable interface as an example, and this example is perfect to illustrate the answer to this question. I quote the official Java doc:
In addition, Runnable provides the means for a class to be active while not subclassing Thread.
Here's the point: Inheritance is a convenient way of typing objects. You want to create a thread? Let's subclass the Thread class. You want an object to have different types, let's use mutliple-inheritance. Argh. It doesn't exist in Java. (In C++, if you want an object to have different types, multiple-inheritance is the way to go.)
How to give mutliple types to an object then? In Java, you can type your object directly. That's what you do when your class implements the Runnable interface. Why use Runnable if your a fan of inheritance? Maybe because your class is already a subclass of another class, let's say A. Now your class has two types: A and Runnable.
With multiple interfaces, you can give multiple types to an object. You just have to create a class that implements multiple interfaces. As long as you are compliant with the contracts, it's ok.
Reuse code
This is a difficult subject; I've already quoted the GOF on breaking the encapsulation. Other answer mentionned the diamond problem. You could also think of the Single Responsibility Principle:
A class should have only one reason to change. (Robert C. Martin, Agile Software Development, Principles, Patterns, and Practices)
Having a parent class may give a class a reason to change, besides its own responsibilities:
The superclass’s implementation may change from release to release, and if it does, the subclass may break, even though its code has not been touched. As a consequence, a subclass must evolve in tandem with its superclass (Bloch, item 16).
I would add a more prosaic issue: I always have a weird feeling when I try to find the source code of a method in a class and I can't find it. Then I remember: it must be defined somewhere in the parent class. Or in the grandparent class. Or maybe even higher. A good IDE is a valuable asset in this case, but it remains, in my mind, something magical. Nothing similar with hierarchies of interfaces, since the javadoc is the only thing I need: one keyboard shortcut in the IDE and I get it.
Inheritance howewer has advantages:
It is safe to use inheritance within a package, where the subclass and the superclass implementations are under the control of the same programmers. It is also safe to use inheritance when extending classes specifically designed and documented for extension (Item 17: Design and document for inheritance or else prohibit it). (Bloch, item 16)
An example of a class "specifically designed and documented for extension" in Java is AbstractList.
But Bloch and GOF insist on this: "Favor composition over inheritance":
Delegation is a way of making composition as powerful for reuse as inheritance [Lie86, JZ91]. In delegation, two objects are involved in handling a request: a receiving object delegates operations to its delegate. This is analogous to subclasses deferring requests to parent classes. (GOF p.32)
If you use composition, you won't have to write the same code again and again. You just create a class that handles the duplications, and you pass an instance of this class to the classes that implements the interface. It's a very simple way to reuse code. And this helps you to follow the Single Responsibility Principle and make the code more testable. Rust and Go don't have inheritance (they don't have classes either), but I don't think that the code is more redundant than in other OOP languages.
Furthermore, if you use composition, you will find yourself naturally using interfaces to give your code the structure and the flexibility it needs (see other answers on use cases of interfaces).
Note: you can share code with Java 8 interfaces
And finally, one last quote:
During the memorable Q&A session, someone asked him [James Gosling]: "If you could do Java over again, what would you change?" "I'd leave out classes" (anywhere on the net, don't know if this is true)
This is very old question and java-8 release have added more features & power to interface.
An interface declaration can contain
method signatures
default methods
static methods
constant definitions.
The only methods that have implementations in interface are default and static methods.
Uses of interface:
To define a contract
To link unrelated classes with has a capabilities (e.g. classes implementing Serializable interface may or may not have any relation between them except implementing that interface
To provide interchangeable implementation e.g. Strategy_pattern
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
Organize helper methods in your libraries with static methods ( you can keep static methods specific to an interface in the same interface rather than in a separate class)
Have a look at this related SE question for code example to understanding the concepts better:
How should I have explained the difference between an Interface and an Abstract class?
Coming back to your queries:
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
Interface can contain code for static and default methods. These default methods provides backward compatibility & static methods provides helper/utility functions.
You can't have true multiple inheritance in java and interface is not the way to get it. Interface can contain only constants. So you can't inherit state but you can implement behaviour.
You can replace inheritance with capability. Interface provides multiple capabilities to implementing classes.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Refer to "uses of interface" section in my answer.
Inheritance is when one class derives from another class (which can be abstract) or an Interface. The strongest point of object oriented (inheritance) is not reuse of code (there are many ways to do it), but polymorphism.
Polymorphism is when you have code that uses the interface, which it's instance object can be of any class derived from that interface. For example I can have such a method:
public void Pet(IAnimal animal) and this method will get an object which is an instance of Dog or Cat which inherit from IAnimal. or I can have such a code:
IAnimal animal
and then I can call a method of this interface:
animal.Eat() which Dog or Cat can implement in a different way.
The main advantage of interfaces is that you can inherit from some of them, but if you need to inherit from only one you can use an abstract class as well. Here is an article which explains more about the differences between an abstract class and an interface:
http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
Both Methods Work (Interfaces and Multiple Inheritance).
Quick Practical Short Answer
Interfaces are better when you have several years of experience using Multiple Inheritance that have Super Classes with only method definition, and no code at all.
A complementary question may be: "How and Why to to migrate code from Abstract Classes to Interfaces".
If you are not using many abstract classes, in your application, or you don't have many experience with it, you may prefer to skip interfaces.
Dont rush to use interfaces.
Long Boring Answer
Interfaces are very similar, or even equivalent to abstract Classes.
If your code has many Abstract classes, then its time you start thinking in terms of Interfaces.
The following code with abstract classes:
MyStreamsClasses.java
/* File name : MyStreamsClasses.java */
import java.lang.*;
// Any number of import statements
public abstract class InputStream {
public void ReadObject(Object MyObject);
}
public abstract class OutputStream {
public void WriteObject(Object MyObject);
}
public abstract class InputOutputStream
imnplements InputStream, OutputStream {
public void DoSomethingElse();
}
Can be replaced with:
MyStreamsInterfaces.java
/* File name : MyStreamsInterfaces.java */
import java.lang.*;
// Any number of import statements
public interface InputStream {
public void ReadObject(Object MyObject);
}
public interface OutputStream {
public void WriteObject(Object MyObject);
}
public interface InputOutputStream
extends InputStream, OutputStream {
public void DoSomethingElse();
}
Cheers.
So. There are a lot of excellent answers here explaining in detail what an interface is. Yet, this is an example of its use, in the way one of my best colleagues ever explained it to me years ago, with what I have learned at university in the last couple of years mixed in.
An interface is a kind of 'contract'. It exposes some methods, fields and so on, that are available. It does not reveal any of its implementation details, only what it returns, and which parameters it takes. And in here lies the answer to question three, and what I feel is one of the greatest strengths of modern OOP:
"Code by addition, Not by modification" - Magnus Madsen, AAU
That's what he called it at least, and he may have it from some other place. The sample code below is written in C#, but everything shown can be done just about the same way in Java.
What we see is a class called SampleApp, that has a single field, the IOContext. IOContext is an interface.
SampleApp does not care one wit about how it saves its data, it just needs to do so, in its "doSomething()" method.
We can imagine that saving the data may have been more important than HOW it was saved at the beginning of the development process, so the developer chose to simply write the FileContext class. Later on, however, he needed to support JSON for whatever reason. So he wrote the JSONFileContext class, which inherits FileContext. This means that it is effectively an IOContext, which has the functionality of FileContext, save the replacement of FileContexts SaveData and LoadData, it still uses its 'write/read' methods.
Implementing the JSON class has been a small amount of work, comparing to writing the class, and having it just inherit IOContext.
The field of SampleApp could have been just of type 'FileContext', but that way, it would have been restricted to ever only using children of that class. By making the interface, we can even do the SQLiteContext implementation, and write to a database, SampleApp will never know or care, and when we have written the SQL lite class, we need only make one change to our code: new JSONFileContext(); instead becomes new SQLiteContext();
We still have our old implementations and can switch back to those if the need arises. We have broken nothing, and all the changes to our code are half a line, that can be changed back within the blink of an eye.
so: Code by addition, NOT by modification.
namespace Sample
{
class SampleApp
{
private IOContext context;
public SampleApp()
{
this.context = new JSONFileContext(); //or any of the other implementations
}
public void doSomething()
{
//This app can now use the context, completely agnostic of the actual implementation details.
object data = context.LoadData();
//manipulate data
context.SaveData(data);
}
}
interface IOContext
{
void SaveData(object data);
object LoadData();
}
class FileContext : IOContext
{
public object LoadData()
{
object data = null;
var fileContents = loadFileContents();
//Logic to turn fileContents into a data object
return data;
}
public void SaveData(object data)
{
//logic to create filecontents from 'data'
writeFileContents(string.Empty);
}
protected void writeFileContents(string fileContents)
{
//writes the fileContents to disk
}
protected string loadFileContents()
{
string fileContents = string.Empty;
//loads the fileContents and returns it as a string
return fileContents;
}
}
class JSONFileContext : FileContext
{
public new void SaveData(object data)
{
//logic to create filecontents from 'data'
base.writeFileContents(string.Empty);
}
public new object LoadData()
{
object data = null;
var fileContents = loadFileContents();
//Logic to turn fileContents into a data object
return data;
}
}
class SQLiteContext : IOContext
{
public object LoadData()
{
object data = null;
//logic to read data into the data object
return data;
}
public void SaveData(object data)
{
//logic to save the data object in the database
}
}
}
Interfaces
An interface is a contract defining how to interact with an object. They are useful to express how your internals intend to interact with an object. Following Dependency Inversion your public API would have all parameters expressed with interfaces. You don't care how it does what you need it to do, just that it does exactly what you need it to do.
Example: You may simply need a Vehicle to transport goods, you don't care about the particular mode of transport.
Inheritance
Inheritance is an extension of a particular implementation. That implementation may or may not satisfy a particular interface. You should expect an ancestor of a particular implementation only when you care about the how.
Example: You may need a Plane implementation of a vehicle for fast transport.
Composition
Composition can be used as an alternative to inheritance. Instead of your class extending a base class, it is created with objects that implement smaller portions of the main class's responsibility. Composition is used in the facade pattern and decorator pattern.
Example: You may create a DuckBoat (DUKW) class that implements LandVehicle and WaterVehicle which both implement Vehicle composed of Truck and Boat implementations.
Answers
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Interfaces are not inheritance. Implementing an interface expresses that you intend for your class to operate in the way that is defined by the interface. Inheritance is when you have a common ancestor, and you receive the same behavior (inherit) as the ancestor so you do not need to define it.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
Interfaces do not achieve multiple inheritance. They express that a class may be suitable for multiple roles.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
One of the major benefits of interfaces is to provide separation of concerns:
You can write a class that does something with another class without caring how that class is implemented.
Any future development can be compatible with your implementation without needing to extend a particular base class.
In the spirit of DRY you can write an implementation that satisfies an interface and change it while still respecting the open/closed principal if you leverage composition.
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing an interface then it is inheritance? We are not using its code.
It is not equal inheritance. It is just similiar. Let me explain:
VolvoV3 extends VolvoV2, and VolvoV2 extends Volvo (Class)
VolvoV3 extends VolvoV2, and VolvoV2 implements Volvo (Interface)
line1: Volvo v = new VolvoV2();
line2: Volvo v = new VolvoV3();
If you see only line1 and line2 you can infer that VolvoV2 and VolvoV3 have the same type. You cannot infer if Volvo a superclass or Volvo is an interface.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritances?
Now using interfaces:
VolvoXC90 implements XCModel and Volvo (Interface)
VolvoXC95 implements XCModel and Volvo (Interface)
line1: Volvo a = new VolvoXC90();
line2: Volvo a = new VolvoXC95();
line3: XCModel a = new VolvoXC95();
If you see only line1 and line2 you can infer that VolvoXC90 and VolvoXC95 have the same type (Volvo). You cannot infer that Volvo is a superclass or Volvo is an interface.
If you see only line2 and line3 you can infer that Volvo95 implements two types, XCModel and Volvo, in Java you know that at least one has to be an interface. If this code was written in C++, for instance, they could be both classes. Therefore, multiple inheritances.
Q3. Anyhow, what is the benefit of using Interfaces? They are not having any code. We need to write code again and again in all classes we implement it.
Imagine a system where you use a VolvoXC90 class in 200 other classes.
VolvoXC90 v = new VolvoXC90();
If you need to evolve your system to launch VolvoXC95 you have to alter 200 other classes.
Now, imagine a system where you use a Volvo interface in 10,000,000 classes.
// Create VolvoXC90 but now we need to create VolvoXC95
Volvo v = new VolvoFactory().newCurrentVolvoModel();
Now, if you need to evolve your system to create VolvoXC95 models you have to alter only one class, the Factory.
It is a common sense question. If your system is composed only of few classes and have few updates use Interfaces everywhere is counterproductive. For big systems, it can save you a lot of pain and avoid risk adopting Interfaces.
I recommend you read more about S.O.L.I.D principles and read the book Effective Java. It has good lessons from experienced software engineers.
Interfaces are made so that a class will implement the functionality within the interface and behave in accordance with that interface.
I have a class with 5 methods. 3 of these methods just have to be opened by other classes in the same package and 2 have to be opened by other classes in an other package.
as example:
void setTimeArray(int[] zeitArray) {
this.timeArray = timeArray ;
}
public int[] getTimeArray() {
return timeArray ;
}
now I was wondering what I should make:
should I make the 3 methods protected and the 2 other public?
or
should I make an interface for the 2 methods?
so what would be cleaner and better for the performance of my application and why?
You seem confused about the use of public, protected, etc. The public methods in your class comprise the public interface of your class. When you design your class, you decide what functionality you want to expose to consumers of your class.
You should only make methods protected IMO for polymorphism. If you are making a method protected so that another class in the package can get at internals, etc., then it is probably a bad class design. You should not make a method protected just because no other classes are using it right now. If you need to use it from another class in the future, you'd have to change the class.
You shouldn't need to create an interface if there aren't multiple concrete classes implementing that interface.
The public interface of a class should flow pretty naturally if you get the OOP paradigm. The decisions should involve more about how to expose function than what to expose.
If there is a single "subject" that is common to the 2 methods but not to the other 3, consider splitting up the class into 2 different classes. If you do so, consider moving the class with the 2 methods to the package in which it will be used (if it makes sense in terms of the "subject" of that package).
In any case, use the lowest visibility that allows you to do what you wish to do.
Also, prefer default visibility to protected (the difference is that protected is like default, but also allows for subclasses in different packages to access those methods).
As the 3 methods of your class are access by the classes of the same package then no need to have a protected access modifier rather you can use default. protected should be used when you want your subclass to access the methods.
and about the public methods you can go for interface if you think you have a similar class which has these two methods implemented in it. so that through interface you can relate them.
You should write the interface as soon as you think, that you might use or need it ;)
In addition to the interface: keeping the non-interface methods protected is a valid solution for your problem.
Don't care about performance. Programming against interfaces or using access modifiers like public, protected or private has no performance impact.
Why are all methods in an interface definition implicitly public? Why does it not allow a protected method?
Because an interface is supposed to mean "what you can see from outside the class". It would not make sense to add non-public methods.
Although the often quoted reason is that "interfaces define public APIs", I think that is an over-simplification. (And it "smells" of circular logic too.)
It would not be meaningless to have interfaces that have a mixture of access modifiers; e.g. partly public and partly restricted to other classes in the same package as the interface. In fact, in some cases this could be down-right useful, IMO.
Actually, I think that the part of reasoning behind making members of an interface implicitly public is that it makes the Java language simpler:
Implicitly public interface members are simpler for programmers to deal with. How many times have you seen code (classes) where the method access modifiers were chosen seemingly at random? A lot of "ordinary" programmers have difficulty understanding how best to manage Java abstraction boundaries1. Adding public/protected/package-private to interfaces makes it even harder for them.
Implicitly public interface members simplify the language specification ... and hence the task for Java compiler writers, and the folks who implement the Reflection APIs.
The line of thinking that the "interfaces define public APIs" is arguably a consequence (or characteristic) of the simplifying language design decision ... not the other way around. But in reality, the two lines of thought probably developed in parallel in the minds of the Java designers.
At any rate, the official response to the RFE in JDK-8179193 makes it clear that the Java design team decided2 that allowing protected on interfaces adds complexity for little real benefit. Kudos to #skomisa for finding the evidence.
The evidence in the RFE settles the issue. That is the official reason why that has not been added.
1 - Of course, top-gun programmers have no difficulty with these things, and may welcome a richer palette of access control features. But, what happens when their code is handed over to someone else to maintain?
2 - You may disagree with their decision or their stated reasoning but that is moot.
I have to say that this question has been re-opened by the introduction of default methods in Java 8. The project that I am working on right now is, similar to the base nature of an interface, meant to abstract intention from implementation.
There are several cases in which I could drastically simplify my code with a "default protected" method. It turns out that that doesn't actually work, as interfaces still stick to Java 7 logic. A normal protected method doesn't especially make any sense, for the reasons mentioned above; but if a default public method requires a low-level resource that will not likely change and can be provided by a protected method, it seems to me that having "default protected" work would not only maintain cleaner code, it would protect future users from accidental abuses.
(This tragically does not change the fact that I still need to over-complicate my code with otherwise unnecessary abstracts; but I do intend to put a feature request in at Oracle.)
Several answers here employ circular reasoning to explain why interface methods can't be protected: it's because they have to be public, so obviously they can't be protected!
That explains nothing, but fortunately someone raised an enhancement request for protected methods in interfaces as a JDK bug a couple of years ago, which sheds some light on the issue:
Protected methods in interfaces: share across packages
Since modifiers are a bit limited in Java, a way to share methods
across packages is restricted to public methods. Sometimes it is
dangerous to make a method public, but it needs to be because of the
lack of proper modifiers. My solution overcomes this limitation.
The java language specification doesn't currently allow the protected
modifier for interface methods. We can take advantage of this fact and
use protected for interface methods for this new feature.
If an interface method is marked protected and the interface is
implemented by a class in another package, the method would not need
to be public, but could also be private or at least package protected.
The method is visible, what ever the class declares it to be and
additionally visible in the source package of the interface (and sub
packages?).
This way we could share certain methods across well known packages.
And this is the response to that enhancement request, which was closed with status Won't fix:
This proposal attempts to solve a problem in a way that adds
complexity and special cases for little actual gain. A typical way to
solve this problem is to have a private class that implements a public
interface. The implementation methods are public, but are within a
private class, so they remain private.
An alternative available starting in Java 9 is to make classes and
methods public, but within a module that has a qualified-export to
specific "friend" modules instead of being exported to the general
public.
So the authoritative takeaways from that bug report are:
The current situation is not going to change; interfaces are unlikely to ever support protected methods.
The justification for not supporting protected methods in interfaces is that it "adds complexity and special cases for little actual gain".
Since Java 9 there is an alternative approach for providing package level access to methods. Use the Java Platform Module System (JPMS) to "make classes and methods public, but within a module that has a qualified-export to specific "friend" modules instead of being exported to the general public".
Because interfaces define public APIs. Anything that's protected is an internal detail which does not belong in an interface.
You can use abstract classes with protected abstract methods, but interfaces are restricted to public methods and public static final fields.
I strongly feel that interfaces should allow protected methods; who said that interfaces have to be visible to everyone in the whole world? As to your point that it might confuse "ordinary" (read:incompetent) programmers: So much of OOP is about properly structuring objects, classes, packages etc., if a programmer has a hard time with doing all that properly, he has a much bigger problem. Java was built for that type of thing.
Perhaps, because it is an interface, i.e. it is there to tell clients what they can do with instances, rather than to tell them what they can not do.
Since an implementing class must implements ALL the methods declared in your interface, what would happen if your implementing class was in a different package ?
Declaring internal subinterfaces is a good practice, but you can not declare your internal methods as protected in an interface in Java, technically.
Of course, you can create another interface for internal use which extends the public interface:
package yourpackage;
public interface PublicInterface {
public void doThing1();
public void doThing2();
public void doThing3();
}
package yourpackage;
interface InternalInterface extends PublicInterface {
void doAnyInternalThing1();
void doAnyInternalThing2();
}
You may use the InternalInterface interface inside the package, but you should accept any subtype of PublicInterface (in public methods):
package yourpackage;
public class SomeClass {
public void someMethod(PublicInterface param) {
if (param instanceof InternalInterface) {
// run the optimized code
} else {
// run the general code
}
}
}
Outside the package users can use PublicInterface without problems.
Usually programmers create abstract classes in similar situations. However, in this case we lose the benefits of multiple inheritance.
Interface If you want to use something like you described go on with abstract classes or nested interfaces.
An exerpt from the Code Style about interface variables, but still apply to methods though:
Interface variables are implicitly public because interfaces are intended to provide an Application Programming Interface (API) that is fully accessible to Java programmers to reference and implement in their own applications. Since an interface may be used in Java packages that are different from their own, public visibility ensures that program code can access the variable.
The only scenario where it would make sense is when you want to restrict visibility to the same package. All the other uses of protected are not applicable. Specifically, protected methods are often used to provide access to some details of lower level implementations for descendants. But declaring that in an interface doesn't make sense, as there's no lower level implementation to expose.
And even the package scenario is not really what interfaces are about.
To achieve what you probably want, you need two interfaces, one for internal use and one that you expose in the public API. (With the internal one possibly, but not necessarily extending the public one.) Or, as others pointed out, an abstract superclass.
Non-public members are generally used by public members. For example, AbstractList.removeRange(int, int) is used by AbstractList.clear(), and overriding it will improve the performance of clear.
If protected methods are allowed in interfaces, it means that most public default implementations will rely on these methods. If a subclass does not need default implementations and override all public methods, then all non-public methods will no longer be useful. And if they are abstract, we will still have to override them, which makes subclasses complicated.
Protected methods are always accessible by sub-class only if subclass extends the base class.
In case of interface, subclass never extends the interface. It implements the interface.
Protected methods are accessible via extend and not with implement.
Interfaces are meant to expose methods to the outer world. Thus these methods are public by nature. However, if you want to introduce abstraction within the same family of classes it is possible by creating another level of abstraction between your interface and implementation class, i.e. an abstract class. An example is demonstrated below.
public interface MyInterface {
public void publicMethod(); // needs to be public
}
public abstract class MyAbstractClass implements MyInterface {
#Override
public void publicMethod() {
protectedMethod(); // you can call protected method here
// do other stuff
}
protected abstract void protectedMethod(); // can be protected
}
public class MyClass extends MyAbstractClass {
#Override
protected void protectedMethod() {
// implement protected method here, without exposing it as public
}
}
I know this is very late/old and I am sure that by now you have a lot more experience than me, so if this helps anyone, cheers, ...
I've found a way that keeps things comfortably cohesive, that prevents the usage of objects when dealing with protected's in-package.
In hindsight this seems ridiculously easy, but the fact of the matter is that the goal of whatever is you want to achieve with a piece of code, becomes 10 times more difficult if you spend any amount of time to try to accommodate it to standards and/or adjusts for code reusability.
The reality is that the order, will unfold as you go..
But I made a chart cause it has helped me in something that, depending on the problem can easily mind-bend me.
public interface CommonPublics {
void publicInAll();
}
public static abstract class CommonProtecteds implements CommonPublics {
protected abstract void protectedInAll();
}
public interface MyObjectPublics {
void myObjectPublic();
}
public static class MyObject extends CommonProtecteds implements MyObjectPublics {
#Override
public void publicInAll() {
}
#Override
protected void protectedInAll() {
}
#Override
public void myObjectPublic() {
}
}
Now when you need to deal with protecteds within the same package, instead of dealing with MyObject, you can deal with CommonProtecteds instead.
Now you could in theory bring whatever logic that handles protected's inside the abstract and that's up to you, but if for whatever reason you are dealing with concurrency, is better to keep everything as tight and as close to the synchronized body as possible. so whatever the protected is required to deal with that may be required inside different locked locations is better placed in the object that will handle it.
I'm developping a server application in Java. The server need two type of server classes. These classes have some methods in common, the code in these methods is exactly the same. So i create an abstract super-class containing all the shared code, and both classes are inheriting it. But, there is some part of the code that need to be precised by subclasses. I mean that the superclass "rely" on subclasses methods.
Here is a purified example of what i mean:
public abstract class AbstractServer
{
public void loadConfig(String configPath)
{
//Load the configuration file.
//This code is exactly the same for subclasses.
}
public void startRMI(int port)
{
//Create an empty RMI registry.
//This part also need to be identical.
//Here' where the superclass "rely" on subclasses.
fillRegistry(); //Call the method overwritten by subclasses.
}
/**
Bind remote objects in the RMI registry
*/
protected abstract void fillRegistry(); //This method will be overriten by subclasses.
}
I feel that it's really bad to make it like that, but i can't find another cleaner way to do it.
So, what i want is some advice on how i could make it better.
Thanks, and sorry for my bad english.
Your approach is just fine. Stick with it buddy.
I feel your 'philosophical need' to understand it. Base class 'relying' on the subclass is fine as long as the base class is abstract. It knows that some things have to be registered at this point, but it doesn't have the faintest clue about what exactly to be registered. So the high-level process is encoded in the base class with 'holes' that can be plugged in by the derived class. The high level process and the position of the 'hole' itself is valuable and this justifies the implementation of the base class. The derived classes just follow the fundamental OO principle of 'coding by difference' and plugs the 'holes'.
Looks about right to me after your edits (assuming that you left out the Exception throwing part for readability) :)
All three methods would need to raise exceptions in a real world case.
Super class is inherited by sub-class. You can write methods in super class which you want to make common and leave it untouched. For the other part of code which you want it to be overwritten by sub classes define other set of methods in super class. write methods in sub-classes also. when u call method from sub-class u can put to call super-class method's
in short u have to write methods in sub class to over write the methods of superclass.
I would also make sure that your superclass is actually abstract. In this snippet it isn't. Overall though, looks decent.
Also consider declaring any instance variables in your superclass that classes that extend it will need as well.
First, there is nothing wrong with requiring subclasses' implementation in abstract (base) classes. It's just something that should not get abused, IMO. However, if I had to avoid it, I would make the ServerClass not abstract at all, and define every method of it. Instead, I would create RegistryFactory classes and pass them to the ServerClass :
class ServerClass {
public void startRMI(int port, RegistryFactory rf) {
// ...
rf.fillRegistry(this);
}
}
interface RegistryFactory {
/**
* Implement this method
*/
public void fillRegistry(ServerClass server);
}
public class RMIRegistryFactory implements RegistryFactory {
public void fillRegistry(ServerClass server) { /* ... */ }
}
Or something like that.
Your approach is fine, but it needs a simple improvement to make it perfect - make the startRMI() method final:
public final void startRMI(int port) {
fillRegistry();
}
This way you will prevent that someone overrides it (maybe because of not knowing that everything in startRMI() should be reused and that only fillRegistry() has to be customized).
Your solution generally matches the template method design pattern:
The template method is a method in a superclass, usually an abstract
superclass, and defines the skeleton of an operation in terms of a
number of high-level steps. These steps are themselves implemented by
additional helper methods in the same class as the template method.
The helper methods may be either abstract methods, for which case
subclasses are required to provide concrete implementations, or hook
methods, which have empty bodies in the superclass. Subclasses can
(but are not required to) customize the operation by overriding the
hook methods. The intent of the template method is to define the
overall structure of the operation, while allowing subclasses to
refine, or redefine, certain steps. (Wikipedia)
Given the above, the method startRMI() is a template method which defines the skeleton of an operation by using a number of high-level steps (in your case it's only one step but this doesn't make a difference). The method fillRegistry() in your example is a high-level step - it's defined as an abstract method in the superclass and has a concrete implementation in the superclasses.
On the other side, if you would override the method startRMI() in a subclass, this would not be OK anymore. That's why you should make it final to avoid confusion - this way someone who creates a subclass will know that he must implement fillRegistry() (since it's abstract) but should not change the implementation of startRMI (since it's final).
Since this is a commonly used design pattern, I wouldn't worry at all if this solution is OK, a lot of people are doing it like that and everyone who knows design patterns will recognize it, I think it feels very natural even for developers who don't know the design pattern.