Abstract class and interface together? - java

I have a section of my code where some classes are implementing an interface.
It feels correct, but there is a little duplication among the child classes - namely 3 methods.
So this is screaming out to use an abstract class.
My question is, will there be any cons in using both abstract class and interface in the following situations:
Abstract class to implement the interface and child classes to extend the abstract class
Child classes to extend the abstract class and implement the interface
Or
Should abstract classes and interfaces not be used together at all like this?

It's perfectly normal to use these two together. Consider for instance AbstractList (implementing List) and AbstractMap (implementing Map) in the JDK.
My knee-jerk reaction would have been to have the abstract class implement the interface and then have the concrete classes derive from it:
abstract class Base implements TheInterface {
/* ...shared methods... */
}
class Concrete1 extends Base { }
class Concrete1 extends Base { }
But your question raising the other possibility made me think, and I can't see much of an argument against doing it that way:
abstract class Base {
/* ...shared methods... */
}
class Concrete1 extends Base implements TheInterface { }
class Concrete1 extends Base implements TheInterface { }
Further, I can see an argument for doing it that way, specifically that it removes the coupling between the abstract class and the interface. If you have another class that needs the functionality Base provides but doesn't need to implement the interface, you have the flexibility to do that.
There's also a third option: Composition. You could not have an abstract class at all, but rather have the multiple concrete classes that implement the interface use a common helper class in their implementation:
class Helper {
/* ...shared methods... */
}
class Concrete1 implements TheInterface {
/* ...uses instance of Helper */
}
class Concrete1 implements TheInterface {
/* ...uses instance of Helper */
}
This has that same flexibility, in another form.

I do not think there is a rule of thumb as such. When designing try and follow the SOLID principles to figure out if what you are doing is good or bad. You can find these principles over here. In this particular case, I would think you should ensure you are abiding by the "Open-Close Principle".

Personally I prefer the statement that an abstract class is a background for other classes, so if three other classes have something common, their common ancestor, the abstract class created only for those three other classes, should provide also code from the interface. This would make the abstract class "complete" (in its way) providing all these properties and methods that the three classes share.
However, it finally makes no difference if all of them would implement the same interface. Making abstract class giving everything that is common is in my opinion a more clear way. It's then easier to compare classes by looking only at this what differs.

Related

Abstract Class Vs. [Interface+Inheritance] in Java

In context of Java, could a class replace the need of extending an abstract class by extending another non-abstract class and implementing an interface together, both of which combined have all the methods(abstract and implemented), of an abstract class?
In context of Java, could a class replace the need of extending an
abstract class by extending another non-abstract class and
implementing an interface together, both of which combined have all
the methods(abstract and implemented), of an abstract class?
Can it? Yes
Should it? No
An abstract class can be replaced by a concrete one, but you will be altering your system.
Do remember: an abstract class can not be instantiated, nor should it be, since it's not 'concrete enough' to make sense for your business. (If it does, it shouldn't have been an abstract class to begin with)
If you make it concrete, you risk that developers will use instances of the (what-should-be) abstract class.
If you change it the way you propose:
public void doSomething(MyAbstractClass instance){
// here we know there is an implementation provided by a subclass
}
would become
public void doSomething(MyShouldBeAbstractClass instance){
// here they can pass instances of the base class, which might have unsupported methods
}
For instance:
public String getConcreteInformation(){
throw new UnsupportedOperationException("Should be called on a child class");
}
and could lead to a lot of nasty bugs

Do Abstract classes need to implement an entire interface in java 7?

I need a group of different classes to implement a certain interface. However, a lot of those classes, but not all of them, need a same implementation for some of the methodes defined in the interface. I was wondering if I could make an abstract class implement the interface and only create the methods that are the same for those classes?
For example, I have interface A:
public interface A{
public returnType method1(){};
public returnType method2(){};
}
Can I do this:
public abstract class AbstractPartialA implements A{
#Override
public returnType method1(){
implementation
}
}
and than have the classes extending from this Abstract class implement the remaining methods that are required to fulfill the interface?
Yes, you can, that is the exact purpose of abstract classes.
Do Abstract classes need to implement an entire interface in java 7?
And the answer is " NO ". Abstract class can implement entire interface or it can implement only some methods of an interface.
Case-1
If it implements entire interface and is still declared as 'abstract', it means we don't want other(people who are going to use our class) to create object for our class
Example of such class is HttpServlet in javax.servlet.http . Here HttpServlet class doesn't have any abstract method, but still it is declared as 'abstract'
Case-2
Simple, if the class doesn't implement any one of the method of an interface, then it is declared as 'abstract'. Now it will be the responsibility of the other class which extends the abstract class to provide the implementation of such method which is not implemented by 'abstract class'
You can, and when you try to extend from AbstractPartialA Java will ask you to:
Implement all methods declared in implemented interfaces and not implemented
Implement all methods declared as abstract in superclasses
Remember that a class is considered to implement all interfaces implemented by its superclasses, not just the ones specifically written after the implements keyword in this class' declaration. This applies both to the types of the class (and thus the types of its references) and to the methods it is required to implement.

restriction of method while implementing an interface

I have two methods in an interface:
public interface MyInterface {
public void methodOne();
public void methodTwo();
}
public class MyClass implements MyInterface{
public void methodOne(){
//implementation code
}
public void methodTwo(){
//implementation code
}
}
Can I restrict one of them while implementing the interface?
You must implement all methods of your interface, unless the class implementing the interface is abstract.
If by restrict you mean that you want to predefine one or more of the methods, then you can use an abstract class instead of the interface. Abstract methods in an abstract class are methods that must be implemented by any class that extends the abstract class. Non-abstract methods are actually implemented in the abstract class, itself.
For example,
public abstract class MyClass
{
abstract void methodOne();
void methodTwo()
{
//implementation code
}
}
public class MyOtherClass extends MyClass
{
void methodOne()
{
//implementation code
}
}
Here's a reference for Abstract Classes and Methods.
EDIT 1 (in response to comment):
I'm not really sure what you mean by a burden. All I'm saying is that if you want all methods to be implemented by the class, then use an interface.
If you only want some of the methods implemented by a class, then you can either use an abstract class instead of the interface
or
If it makes sense, have an abstract class implement the interface (partially) and then have the remainder of the methods implemented by whatever extends the abstract class.
Both approaches are reasonable. It depends on what you really need to do.
EDIT 2 (in response to additional comments):
Providing one user class with additional features seems like the perfect application for just extending the "normal user class" with a "super user" class that has the additional features. If you need an interface for the "super user" class, you can create an interface that extends the interface implemented by the "normal user" class.
No you have to implement all methods if your class implements an interface.
Unless it is abstract.
Check this discussion for more details.
You can use an abstract class; they do not need to implement all the entire interface. However, they cannot be instantiated. You must implement all methods in order to instantiate an implementation of an interface.
Except the abstract class, you are bound to implements all methods of interface.
You can not put restriction on Interface, but YES you can achieve In Abstract class and NO in concrete class.
Couple of solutions :
Either mark the class as abstract. But in that case you cannot instantiate your implementing class.
Simply add black implementation in your class.
Not sure what you mean by "restrict". You have to implement the method. However, you could simply do
public void method1(someargs) {
throw new UnsupportedOperationException();
}
as is done by many Collection implementations.

Why doesn't interfaces implement methods and override them?

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

I've found many questions on abstract classes and interfaces but answer me this: Can an abstract class do everything an interface can?

I'm really confused, and I've read a TON of questions on this topic and I have not been able to pinpoint anything specifically that an interface can do that an abstract class cannot do.
Is there anything an interface can do that an abstract class cannot do?
I am asking in the context of my Java class, but feel free to remove the java tag if it applies to other languages as well (possibly C#?).
Edit: I understand that an abstract class can do things an interface cannot, but if an abstract class can do everything an interface can do, then what is the point of an interface? What does "implement multiple interfaces" mean?
Interfaces as such cannot do what abstract classes do.
This is because abstract classes can contain code - interfaces cannot. But any given class can only have one superclass - extends - as opposed to any number of interfaces - implements, so if you use abstract classes you essentially paint yourself in a corner of the inheritance tree, because your class can only extend a single class.
This limitation does not apply to interfaces, allowing a single class to have many purposes depending on how many interfaces it implements.
You can't inherit from multiple abstract classes in c#, but you can implement multiple interfaces.
I think this may apply to java too
Edit:
You can't inherit from multiple classes. If you have an abstract class called Clonable, and an abstract class called Disposable then you can only inherit one of these classes and you're forced to make a decision about which class your class should be a subtype of:
e.g:
public abstract class Clonable
{
public abstract void Clone();
}
public abstract class Disposable
{
public abstract void Dispose();
}
// MyClass cannot be Disposable too, it is not allowed by the language
public class MyClass : Clonable
{
override void Clone()
{
}
}
Note it is a design decision of the language to allow you only to inherit from one class.
If on the other hand you have interfaces, the language allows you to implement both
e.g.
public interface IClonable
{
void Clone();
}
public interface IDisposable
{
void Dispose();
}
public class MyClass : IClonable, IDisposable
{
void IClonable.Clone()
{
}
void IDisposable.Dispose()
{
}
}
Well read:
http://mindprod.com/jgloss/interface.html
http://mindprod.com/jgloss/interfacevsabstract.html
What does "implement multiple interfaces" mean?
Consider:
public static interface Ifun extends Comparable<Ifun>, Serializable {}//or
public static class Cfun2 implements Comparable<Cfun>, Serializable
When class implements Ifun, then:
Comparable interface imposes a total ordering on the objects of each class that implements it. Objects that implement this interface can be sorted automatically by Collections.sort.
The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
It means object can have more then 1 interface.
Interfaces are non instantiable classes that only contains methods that subclasses can inherit. The only thing that interfaces can do (in java) is that a class can implement many interfaces while a class can only extend 1 abstract class.

Categories