practical situation to use an abstract interface? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was trying to understand when it can be useful to create an abstract interface.
I know that if you create an interface the methods have to be public, so is nice for a service. But what happens if service is an abstract interface? Does that make sense?
If I create a service declared abstract interface and some methods are private, the class that implements this interface sees the private methods and the other (another application's or similar) doesn't see this methods, correct?
I this is a correcte implementation?
Finally after a lot of people that can sleep by my fault I write my solution, ty for waiting.
package cat.base.gpt.domini;
public interface IExpMS extends Serializable{
... methods here..
}
public interface IExpMSDetallGIM extends IExpMS {
more methods here..
}
public interface IExpMSDetallOGC extends IExpMS{
..no methods just inheritance.
}
package cat.base.gpt.domini.impl;
import cat.base.gpt.domini.IClauExpedient;
import cat.base.gpt.domini.IExpMS;
public class ExpMS implements IExpMS{
..atributs and #overide methos interface
}
public class ExpMSDetallGim extends ExpMS implements IExpMSDetallGIM {..}
public class ExpMSDetallOGC extends ExpMS implements IExpMSDetallOGC {..}
*every method is public, atributs are private. maybe i can write methods in the interfaces protected, but i'm not really sure...if someone needs to see full code i can't post or send by email.
if ypu wanna see the databasze views to think about my solution here there are:
![IExpMSDetallGIM4
ty.

Interfaces are always abstract. They define the interface of a class, so they are only about public methods, regardless the language, I think.
And while private methods are implementation detail and NOT the interface, they cannot be declared in an interface.
If you want a private method to be the same in a set of classes, you can create a base abstract class with protected methods.
Abstract means "you cannot create a member of this type".
Interface is just a description of some of the classes' properties. They are always abstract, while you cannot create an instance of an interface.
Look at the link http://www.ronaldwidha.net/2008/06/16/a-good-example-of-abstract-class-vs-interface/ - it describes the code in C#, but it's the same thing, only the keywords differ.

i'm working with java..is the same?so interface = abstract interface?
In Java 7, yes. In Java 7 (or earlier) an interface is implicitly abstract. The interface itself does not include bodies for any of the methods that it specifies, so it makes no sense to create an instance.
In Java 8, it is possible to include default methods in an interface. These default methods have bodies with executable code in them, but (naturally) they cannot refer directly to the state of an instance. (Instance state variables are declared in the classes that implement interface ... and the default methods can't refer to stuff that has not, and may not ever be declared.)
However, you still cannot create an instance of a Java 8 interface, so it is still abstract in the sense that an abstract class is abstract.
You then ask this:
If I create a service declared abstract interface and some methods are private, the class that implements this interface sees the private methods and the other (another application's or similar) doesn't see this methods, correct?
That is correct ... but it is nothing to do with what the abstract keyword means in Java. In fact, that is describing how all Java classes behave ... vis-a-vis the visibility of private members.

The primary purpose of interfaces is to allow multiple different implementations of "the same thing". The user of the interface is not dependent on the particular implementation and this allows for good separation of concerns. New implementations can be added later and the program can be extended, without ever need to modify the code that is using them.
Imagine how you would write a program for summing up numbers from various data sources. You could write one separate program for every type of data source (e.g. csv, xls, database table). But then, the "summing up" logic would be repeated. If you wanted to add a new data source type, you'd have to write a whole program from scratch.
Interfaces allow to make it more flexible. You realize, that your summing up logic needs to operate on a list of numbers. It doesn't care where those numbers come from. So you define an interface:
interface NumberListProvider {
List<Double> readNumbers();
}
Then you make your whole complex algorithm dependent only on this interface and you provide different implementations (concrete classes), reading the numbers from csv, xls or various databases.

Related

Do I need to override a method that is implemented in an abstract class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have an abstract superclass. Some of the methods have implementation in the abstract class. In my subclass would i need to override the implemented method. The method in the subclass does exactly the same as superclass.
public abstract class vehicle {
public int getNumber() {
return 5;
}
}
public class car {
public int getNumber() {
return super.getNumber();
}
}
So my question is, do i need to override the method and include a super call? Or can i just leave it in the super class and not implement it at all in the subclass?
No, you do not. You can just leave it in the super (parent) class and not implement it at all.
The Reason
Basically the idea behind an abstract class (very briefly) is that you can write down common implementations that all the concrete classes derived from the abstract class once, and then not have to override or rewrite them again.
An example like in your case would be if all the vehicles have a number, it is a common property, then there isn't a point in writing the same getNumber() method for each class that derives from that class. The abstract vehicles class is like a 'framework' of sorts, and the concrete classes (car, bus, van) that derive from the vehicle class is the actual class that you instantiate. In this class you can have more specialized variables and methods, (is the car a 2 wheel or 4 wheel? A truck probably doesn't need that method)
Related readings from this SO question: Purpose of Abstract Classes
In short the beauty of abstract classes is that you don't have to be concrete (lol) about every single detail, yet you can have one method for across all common classes, and override them if they are special cases. This helps in maintaining code too (A bug in a common method shared across all classes only requires change in the abstract class and not all of the concrete classes)
Additional Info
Just as additional info, if you did use an interface and NOT an abstract class, then you would HAVE to override each method there, as an interface does not contain the implementation, only the design. This link helped explain things to me last time.
You might also want to read up on Polymorphism and Inheritance, important concepts in all Object oriented Programming (OOP) languages. :)
Note: Also, since I can't comment on your question (not enough rep) yet but have been lurking on SO long enough, don't be discouraged by the downvotes, many here assume you have the right keywords too search for on StackOverflow to get the answer you want but this isn't always the case. Good luck!
You can leave it in the superclass and not implement it in the subclass.
calling
car BMW = new car();
BMW.getNumber();
should grab the superclass method.

Purpose of having super class as an abstract class in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Super class being an abstract class creates an overhead for all its sub classes to compulsorily define its abstract methods. I understand that it's very basic but I need to know why do programmers usually make super class as an abstract class, though we can do similar things using a super class as a non abstract class.
An abstract superclass is one way to provide re-usable code.
You can extend the abstract class and inherit the code. This is sometimes more convenient than using static methods or object composition to share code.
The abstract class can "fix" parts of the code (by making it final). This is called the "template method" pattern (and this is not possible with an interface, which cannot provide final methods).
Of course, you can achieve both with a non-abstract superclass as well.
An abstract class has the additional benefit that it does not have to provide a complete implementation (that would make sense to instantiate on its own), some parts can be left specified, but unimplemented (the abstract methods).
imagine you have a common behaviour where only small details are specific to the implementation - then you can put all the common behaviour in a abstract base class and having some abstract methods that the implementing classes need to fill.
For example a abstract repository base class might implement all the details to contact your server, etc. and concrete repositories just need to fill in the details to read the right object from the right table, etc.
Abstarct classes are meant for 'abstracting'. means if some classes are having common behaviour, instead of writing evry time the same thing in each class, write that in one class and ask the other classes to use it [by making the classes as subclasses to the abstract class]. This is nothing but inheritance. To summarise: Use abstract classes when you want default behaviour for some classes Use interfaces when you want different behaviour different classes.
For More explanations Refer below links:
http://www.javacoffeebreak.com/faq/faq0084.html
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
several usage of abstract class:
act as the protocol when tranfering data between objects, the two customers need not to know other class's structure. ----- just like the interface
define the abstract operation, which hides the detailed implementation of concrete class, for example, I have a class called AbstractPayment, which define the opration of charging money from customer, then the concrete classese of it could be: PaypalPayment, AlipayPayment, BankPayment and others. BUT, for the class customer, it only needs to know the AbstractPayment.
after some time, if you need to add another ConcretePayment, or modify one other payment, the customer class won't change.
Abstraction is largely used in design patterns, I suggest you to read following:
Abstract Factory Pattern
STO

How do I group many interfaces into a common single interface? [duplicate]

This question already has answers here:
Why an interface can not implement another interface?
(7 answers)
Closed 9 years ago.
EDIT: The simple answer to my question is that Java allows one interface to extend multiple other interfaces. This is what answers my logical question of how you group interfaces together in a common interface. This answer did not appear in the dupe question. Also the question was different, it was not about creating interface groups.
Is there a reason in Java you cannot define one interface as implementing other interfaces? The answer I've seen and been dissatisfied with is that "interfaces themselves don't contain implementation, so how could an interface implement other other interfaces?" Well, that's a weak answer in my opinion, because its more a nod to English semantics than it is logical interpretation of the scenario. The logical interpretation of the scenario is since we can define classes to implement many interfaces, why can't we define an interface that itself represents a collection of interfaces.
Suppose you have many classes that you want to each implement a large, common set of many interfaces. As it currently stands, you'd have to explicitly write out the list for each class. This means that if later you had to add another interface to your list of many, you'd have to modify each class. Having all the interfaces consolidated in one "super interface" would allow the programmer to make the change in only one place.
And before you answer "make an abstract superclass that implements the list of interfaces, and have all your subclasses extend that superclass", keep in mind you cannot assume these classes do not already extend classes. One of the whole benefits of the implements keyword is so that you can adapt a class without having to change its taxonomy, right?
I guess the long story short is: Why can't programmers define interfaces that are just groups of other interfaces? Or, maybe the better question is: If I can't define an interface as implementing other interfaces, HOW can I define interfaces that are groups of other interfaces?
For those of you that prefer code, what I'm asking is why instead of doing this...
public class Foo extends ParentClass1 implements IBar1, IBar2, IBar3{
}
public class Baz extends ParentClass2 implements IBar1, IBar2, IBar3{
}
...wouldn't it make more sense for Java to allow this:
public interface IAllBar implements IBar1, IBar2, IBar3{
}
public class Foo extends ParentClass1 implements IAllBar{
}
public class Baz extends ParentClass2 implements IAllBar{
}
That way, later, if I create IBar4 I only have to modify IAllBar.java instead of Foo.java AND Baz.java.
Edit: So according to below answers I can define IAllBar to EXTEND all those interfaces and I'll get exactly what I want. I'm glad some people are willing to read an entire post before jumping to the bottom to post mean responses.
You can define an interface that's a collection of other interfaces. Its called extending an interface. You can extend multiple interfaces.
As for why you can't define methods in an interface, it's how Java interfaces were defined. And the problem you speak of are the consequences of single inheritance.
However you will be pleased to know that in the new upcoming Java 8 there's an feature called Virtual Extension Methods which addresses the large code base problems you speak of.
Personally I think it's useful in legacy code bases for quick refactoring, but if the system is well designed you should be able to get rid of the default implementations later. And overusing this feature will only result in all the disadvantages of multiple inheritance.
Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
I believe what you should do is extend interfaces.
You could do this as shown below:
public interface ManBearPig implements Man, Bear, Pig {
//interface body
}
You could then implement ManBearPig where you need it.
The thing you need to keep in mind is that interfaces support multiple inheritance.
To understand this consider the idea that interfaces Man, Bear, and Pig might each have the method walk() included within them.
If you were to implement ManBearPig in a class and call the walk() method it would implement the walk method of Man, Bear, and pig simultaneously.
According to my understanding, your problem statement is:
How to design a Type hierarchy where a group of Classes implement same set of Interfaces and a number of behaviors exposed by the interfaces have common implementation.
This kind of design problem can be solved in Java in the following way (explaining by your example code)
public abstract class AbstractAllBar implements IBar1, IBar2, IBar3{
/* Provide implementations of methods whose behavior remains unchanges for all of it's children classes.*/
}
Now this abstract class can be extended by the classes who have common set of behaviors as defined by the abstract class AbstractAllBar.
public class ParentClass1 extends AbstractAllBar {
.......
}
public class ParentClass2 extends AbstractAllBar {
.......
}
public class Foo extends ParentClass1 {
}
public class Baz extends ParentClass2 {
}
This kind of abstract classes provide Skeleton Implementation. Examples of Skeleton Implementation can be found in Collection API. You can refer source code of AbstractList and AbstractSet to make it more clear.

Java: protected method in interface

Okay I know this question has been asked a few times, but I need an advice on my specific case. There are Encodable's and Decodable's, and a Message is both an Encodable and a Decodable:
interface Encodable { void encode(); }
interface Decodable { void decode(); }
class Message implements Encodable, Decodable { ... }
void processEncodable(Encodable encodable) {
...
encodable.encode();
...
}
There are other Encodable's (and Decodable's) besides Message and they need to be processed in processEncodable. So far so good, but the problem is that I want to hide encode() and decode() from outside the package, and Java interface doesn't allow protected/private methods. One might suggest abstract classes, but as you can see Message should inherit both Encodable and Decodable, so that's not the case. Any suggestions?
These days I'm very much into Scala, and Scala traits allow protected/private methods and that's more intuitive IMHO. I've gone through a few answers mentioning Java interface's design philosophy, but I don't really understand why it shouldn't permit protected methods if interface was introduced as an alternative to multiple inheritance, while abstract classes do..
Being an alternative doesn't imply that it is a full substitute. Interfaces are Service Contracts and so they expose the functionalities that a certain class provides to its clients, being a client anyone with access to the interface.
If you want to hide encode and decode from outside the package (that means that your logic should also stay in the package with the Message class) don't expose them through the interface and, instead, allow them to be protected (or package private) methods of your Message class (or a superclass, if various classes will be encodable/decodable).
This is not an isolated rule. There are mechanisms to achieve what you want without breaking the concept of an Interface. Just think about this: What good does that method to the interface if you can access it only inside a package? What's the point of having such methods in an interface if they can be class methods that are, also, available to the members of the package with the proper modifiers?

Abstract class vs Interface in Java

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.

Categories

Resources