Tagging Interfaces in Java - java

What are tagging interfaces and what are they used for?

A tagging interface typically has some magic associated with it: either directly built into the VM, or using reflection. Because the magic could technically apply to any class, you use the tagging to indicate that you thought well about the magic and whether it applies to your class.

Because sometimes, it really makes sense if some property of a type can be used as a type itself - Serializable comes to mind. If I make a method like this:
public void save(Object data){ ... }
... you don't really know how that data will be saved. VM serialization? Bean property serialization? Some homebrewed scheme? Whereas if you write it like this:
public void save(Serializable data){ ... }
... it is quite clear (if only the designer of ObjectOutputStream had used this possibility!). Sometimes it makes sense to use annotations when you want to add meta-data to types, but in this case, I'd argue for a tagging interface.

The question of marker interfaces vs annotations is discussed in Bloch's "Effective Java", and part of that section is available on google books here

It was used to mentioned some property of a class (like Serializable shows, that the class is allowed to serialize). Now annotations could do this job.

In addition to the other answers marker interfaces can also be used to specify additional properties of a class that is not inherited by some other already-implemented interface. One example of this would be the interface RandomAccess. It denotes a collection that can be accessed randomly without loss of performance and does not have to be accessed via an iterator to achieve that performance.

You can tag your class with a tagging interface to say to your fellow developer and consumer of your class that you explicitely support that functionality. Think of Serializable; someone who needs to persist a Session and uses serialization to do that can safely use an object of your class.
It can be further used in reflection; nowadays it is common to use annotations to do this but in the olden days you can inspect a class, check whether it implements a certain interface (like DAO) and if so, process the object further (I'm thinking about the Entity annotation here).

tagging interfaces are interfaces with no abstract methods inside , they are used to add a data type for the class which implements them and to be a parent interface for other interfaces ( especially with multiple inheritance in interfaces )
public interface name {}
public interface john1 {}
public interface john2 {}
public interface Demo extends john1 , john2 , name {}
** when JVM sees the name interface , it will find out that the Demo will exert a specific cenario .

I would also add you can use tagging interfaces to restrict ownership of an instance:
interface IFlumThing;
interface IFlooThing;
class BaseThing {...}
class FlumThing extends BaseThing implements IFlumThing {};
class FlooThing extends BaseThing implements IFlooThing {};
class Flum {
addThing(IFlumThing thing){...};
}
class Floo {
addThing(IFlooThing thing){...};
}

Related

When an abstract class needs to implement the interface in Java [duplicate]

In one of my interviews, I have been asked to explain the difference between an Interface and an Abstract class.
Here's my response:
Methods of a Java interface are implicitly abstract
and cannot have implementations. A Java abstract class can have
instance methods that implements a default behaviour.
Variables declared in a Java interface are by default final. An
abstract class may contain non-final variables.
Members of a Java interface are public by default. A Java abstract
class can have the usual flavours of class members like private,
protected, etc.
A Java interface should be implemented using keyword “implements”; A
Java abstract class should be extended using keyword “extends”.
An interface can extend another Java interface only, an abstract class
can extend another Java class and implement multiple Java interfaces.
A Java class can implement multiple interfaces but it can extend only
one abstract class.
However, the interviewer was not satisfied, and told me that this description represented "bookish knowledge".
He asked me for a more practical response, explaining when I would choose an abstract class over an interface, using practical examples.
Where did I go wrong?
I will give you an example first:
public interface LoginAuth{
public String encryptPassword(String pass);
public void checkDBforUser();
}
Suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 methods:
public class DBMySQL implements LoginAuth{
// Needs to implement both methods
}
public class DBOracle implements LoginAuth{
// Needs to implement both methods
}
public class DBAbc implements LoginAuth{
// Needs to implement both methods
}
But what if encryptPassword() is not database dependent, and it's the same for each class? Then the above would not be a good approach.
Instead, consider this approach:
public abstract class LoginAuth{
public String encryptPassword(String pass){
// Implement the same default behavior here
// that is shared by all subclasses.
}
// Each subclass needs to provide their own implementation of this only:
public abstract void checkDBforUser();
}
Now in each child class, we only need to implement one method - the method that is database dependent.
Nothing is perfect in this world. They may have been expecting more of a practical approach.
But after your explanation you could add these lines with a slightly different approach.
Interfaces are rules (rules because you must give an implementation to them that you can't ignore or avoid, so that they are imposed like rules) which works as a common understanding document among various teams in software development.
Interfaces give the idea what is to be done but not how it will be done. So implementation completely depends on developer by following the given rules (means given signature of methods).
Abstract classes may contain abstract declarations, concrete implementations, or both.
Abstract declarations are like rules to be followed and concrete implementations are like guidelines (you can use it as it is or you can ignore it by overriding and giving your own implementation to it).
Moreover which methods with same signature may change the behaviour in different context are provided as interface declarations as rules to implement accordingly in different contexts.
Edit: Java 8 facilitates to define default and static methods in interface.
public interface SomeInterfaceOne {
void usualAbstractMethod(String inputString);
default void defaultMethod(String inputString){
System.out.println("Inside SomeInterfaceOne defaultMethod::"+inputString);
}
}
Now when a class will implement SomeInterface, it is not mandatory to provide implementation for default methods of interface.
If we have another interface with following methods:
public interface SomeInterfaceTwo {
void usualAbstractMethod(String inputString);
default void defaultMethod(String inputString){
System.out.println("Inside SomeInterfaceTwo defaultMethod::"+inputString);
}
}
Java doesn’t allow extending multiple classes because it results in the “Diamond Problem” where compiler is not able to decide which superclass method to use. With the default methods, the diamond problem will arise for interfaces too. Because if a class is implementing both
SomeInterfaceOne and SomeInterfaceTwo
and doesn’t implement the common default method, compiler can’t decide which one to chose.
To avoid this problem, in java 8 it is mandatory to implement common default methods of different interfaces. If any class is implementing both the above interfaces, it has to provide implementation for defaultMethod() method otherwise compiler will throw compile time error.
You made a good summary of the practical differences in use and implementation but did not say anything about the difference in meaning.
An interface is a description of the behaviour an implementing class will have. The implementing class ensures, that it will have these methods that can be used on it. It is basically a contract or a promise the class has to make.
An abstract class is a basis for different subclasses that share behaviour which does not need to be repeatedly created. Subclasses must complete the behaviour and have the option to override predefined behaviour (as long as it is not defined as final or private).
You will find good examples in the java.util package which includes interfaces like List and abstract classes like AbstractList which already implements the interface. The official documentation describes the AbstractList as follows:
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array).
An interface consists of singleton variables (public static final) and public abstract methods. We normally prefer to use an interface in real time when we know what to do but don't know how to do it.
This concept can be better understood by example:
Consider a Payment class. Payment can be made in many ways, such as PayPal, credit card etc. So we normally take Payment as our interface which contains a makePayment() method and CreditCard and PayPal are the two implementation classes.
public interface Payment
{
void makePayment();//by default it is a abstract method
}
public class PayPal implements Payment
{
public void makePayment()
{
//some logic for PayPal payment
//e.g. Paypal uses username and password for payment
}
}
public class CreditCard implements Payment
{
public void makePayment()
{
//some logic for CreditCard payment
//e.g. CreditCard uses card number, date of expiry etc...
}
}
In the above example CreditCard and PayPal are two implementation classes /strategies. An Interface also allows us the concept of multiple inheritance in Java which cannot be accomplished by an abstract class.
We choose an abstract class when there are some features for which we know what to do, and other features that we know how to perform.
Consider the following example:
public abstract class Burger
{
public void packing()
{
//some logic for packing a burger
}
public abstract void price(); //price is different for different categories of burgers
}
public class VegBerger extends Burger
{
public void price()
{
//set price for a veg burger.
}
}
public class NonVegBerger extends Burger
{
public void price()
{
//set price for a non-veg burger.
}
}
If we add methods (concrete/abstract) in the future to a given abstract class, then the implementation class will not need a change its code. However, if we add methods in an interface in the future, we must add implementations to all classes that implemented that interface, otherwise compile time errors occur.
There are other differences but these are major ones which may have been what your interviewer expected . Hopefully this was helpful.
1.1 Difference between Abstract class and interface
1.1.1. Abstract classes versus interfaces in Java 8
1.1.2. Conceptual Difference:
1.2 Interface Default Methods in Java 8
1.2.1. What is Default Method?
1.2.2. ForEach method compilation error solved using Default Method
1.2.3. Default Method and Multiple Inheritance Ambiguity Problems
1.2.4. Important points about java interface default methods:
1.3 Java Interface Static Method
1.3.1. Java Interface Static Method, code example, static method vs default method
1.3.2. Important points about java interface static method:
1.4 Java Functional Interfaces
1.1.1. Abstract classes versus interfaces in Java 8
Java 8 interface changes include static methods and default methods in
interfaces. Prior to Java 8, we could have only method declarations in
the interfaces. But from Java 8, we can have default methods and
static methods in the interfaces.
After introducing Default Method, it seems that interfaces and
abstract classes are same. However, they are still different concept
in Java 8.
Abstract class can define constructor. They are more structured and
can have a state associated with them. While in contrast, default
method can be implemented only in the terms of invoking other
interface methods, with no reference to a particular implementation's
state. Hence, both use for different purposes and choosing between two
really depends on the scenario context.
1.1.2. Conceptual Difference:
Abstract classes are valid for skeletal (i.e. partial) implementations of interfaces but should not exist without a matching interface.
So when abstract classes are effectively reduced to be low-visibility, skeletal implementations of interfaces, can default methods take this away as well? Decidedly: No! Implementing interfaces almost always requires some or all of those class-building tools which default methods lack. And if some interface doesn’t, it is clearly a special case, which should not lead you astray.
1.2 Interface Default Methods in Java 8
Java 8 introduces “Default Method” or (Defender methods) new feature, which allows developer to add new methods to the Interfaces without breaking the existing implementation of these Interface. It provides flexibility to allow Interface define implementation which will use as default in the situation where a concrete Class fails to provide an implementation for that method.
Let consider small example to understand how it works:
public interface OldInterface {
    public void existingMethod();
 
    default public void newDefaultMethod() {
        System.out.println("New default method"
               + " is added in interface");
    }
}
The following Class will compile successfully in Java JDK 8,
public class OldInterfaceImpl implements OldInterface {
    public void existingMethod() {
     // existing implementation is here…
    }
}
If you create an instance of OldInterfaceImpl:
OldInterfaceImpl obj = new OldInterfaceImpl ();
// print “New default method add in interface”
obj.newDefaultMethod(); 
1.2.1. Default Method:
Default methods are never final, can not be synchronized and can not
override Object’s methods. They are always public, which severely
limits the ability to write short and reusable methods.
Default methods can be provided to an Interface without affecting implementing Classes as it includes an implementation. If each added method in an Interface defined with implementation then no implementing Class is affected. An implementing Class can override the default implementation provided by the Interface.
Default methods enable to add new functionality to existing Interfaces
without breaking older implementation of these Interfaces.
When we extend an interface that contains a default method, we can perform following,
Not override the default method and will inherit the default method.
Override the default method similar to other methods we override in
subclass.
Redeclare default method as abstract, which force subclass to
override it.
1.2.2. ForEach method compilation error solved using Default Method
For Java 8, the JDK collections have been extended and forEach method is added to the entire collection (which work in conjunction with lambdas). With conventional way, the code looks like below,
public interface Iterable<T> {
    public void forEach(Consumer<? super T> consumer);
}
Since this result each implementing Class with compile errors therefore, a default method added with a required implementation in order that the existing implementation should not be changed.
The Iterable Interface with the Default method is below,
public interface Iterable<T> {
    public default void forEach(Consumer
                   <? super T> consumer) {
        for (T t : this) {
            consumer.accept(t);
        }
    }
}
The same mechanism has been used to add Stream in JDK Interface without breaking the implementing Classes.
1.2.3. Default Method and Multiple Inheritance Ambiguity Problems
Since java Class can implement multiple Interfaces and each Interface can define default method with same method signature, therefore, the inherited methods can conflict with each other.
Consider below example,
public interface InterfaceA { 
       default void defaultMethod(){ 
           System.out.println("Interface A default method"); 
    } 
}
 
public interface InterfaceB {
   default void defaultMethod(){
       System.out.println("Interface B default method");
   }
}
 
public class Impl implements InterfaceA, InterfaceB  {
}
The above code will fail to compile with the following error,
java: class Impl inherits unrelated defaults for defaultMethod() from
types InterfaceA and InterfaceB
In order to fix this class, we need to provide default method implementation:
public class Impl implements InterfaceA, InterfaceB {
    public void defaultMethod(){
    }
}
Further, if we want to invoke default implementation provided by any of super Interface rather than our own implementation, we can do so as follows,
public class Impl implements InterfaceA, InterfaceB {
    public void defaultMethod(){
        // existing code here..
        InterfaceA.super.defaultMethod();
    }
}
We can choose any default implementation or both as part of our new method.
1.2.4. Important points about java interface default methods:
Java interface default methods will help us in extending interfaces without having the fear of breaking implementation classes.
Java interface default methods have bridge down the differences between interfaces and abstract classes.
Java 8 interface default methods will help us in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.
Java interface default methods will help us in removing base implementation classes, we can provide default implementation and the implementation classes can chose which one to override.
One of the major reason for introducing default methods in interfaces is to enhance the Collections API in Java 8 to support lambda expressions.
If any class in the hierarchy has a method with same signature, then default methods become irrelevant. A default method cannot override a method from java.lang.Object. The reasoning is very simple, it’s because Object is the base class for all the java classes. So even if we have Object class methods defined as default methods in interfaces, it will be useless because Object class method will always be used. That’s why to avoid confusion, we can’t have default methods that are overriding Object class methods.
Java interface default methods are also referred to as Defender Methods or Virtual extension methods.
Resource Link:
When to use: Java 8+ interface default method, vs. abstract method
Abstract class versus interface in the JDK 8 era
Interface evolution via virtual extension methods
1.3 Java Interface Static Method
1.3.1. Java Interface Static Method, code example, static method vs default method
Java interface static method is similar to default method except that we can’t override them in the implementation classes. This feature helps us in avoiding undesired results incase of poor implementation in implementation classes. Let’s look into this with a simple example.
public interface MyData {
default void print(String str) {
if (!isNull(str))
System.out.println("MyData Print::" + str);
}
static boolean isNull(String str) {
System.out.println("Interface Null Check");
return str == null ? true : "".equals(str) ? true : false;
}
}
Now let’s see an implementation class that is having isNull() method with poor implementation.
public class MyDataImpl implements MyData {
public boolean isNull(String str) {
System.out.println("Impl Null Check");
return str == null ? true : false;
}
public static void main(String args[]){
MyDataImpl obj = new MyDataImpl();
obj.print("");
obj.isNull("abc");
}
}
Note that isNull(String str) is a simple class method, it’s not overriding the interface method. For example, if we will add #Override annotation to the isNull() method, it will result in compiler error.
Now when we will run the application, we get following output.
Interface Null Check
Impl Null Check
If we make the interface method from static to default, we will get following output.
Impl Null Check
MyData Print::
Impl Null Check
Java interface static method is visible to interface methods only, if we remove the isNull() method from the MyDataImpl class, we won’t be able to use it for the MyDataImpl object. However like other static methods, we can use interface static methods using class name. For example, a valid statement will be:
boolean result = MyData.isNull("abc");
1.3.2. Important points about java interface static method:
Java interface static method is part of interface, we can’t use it for implementation class objects.
Java interface static methods are good for providing utility methods, for example null check, collection sorting etc.
Java interface static method helps us in providing security by not allowing implementation classes to override them.
We can’t define interface static method for Object class methods, we will get compiler error as “This static method cannot hide the instance method from Object”. This is because it’s not allowed in java, since Object is the base class for all the classes and we can’t have one class level static method and another instance method with same signature.
We can use java interface static methods to remove utility classes such as Collections and move all of it’s static methods to the corresponding interface, that would be easy to find and use.
1.4 Java Functional Interfaces
Before I conclude the post, I would like to provide a brief introduction to Functional interfaces. An interface with exactly one abstract method is known as Functional Interface.
A new annotation #FunctionalInterface has been introduced to mark an interface as Functional Interface. #FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces. It’s optional but good practice to use it.
Functional interfaces are long awaited and much sought out feature of Java 8 because it enables us to use lambda expressions to instantiate them. A new package java.util.function with bunch of functional interfaces are added to provide target types for lambda expressions and method references. We will look into functional interfaces and lambda expressions in the future posts.
Resource Location:
Java 8 Interface Changes – static method, default method
All your statements are valid except your first statement (after the Java 8 release):
Methods of a Java interface are implicitly abstract and cannot have implementations
From the documentation page:
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.
Default methods:
An interface can have default methods, but are different than abstract methods in abstract classes.
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.
When you extend an interface that contains a default method, you can do the following:
Not mention the default method at all, which lets your extended interface inherit the default method.
Redeclare the default method, which makes it abstract.
Redefine the default method, which overrides it.
Static Methods:
In addition to default methods, you can define static methods in interfaces. (A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.)
This makes it easier for you to organize helper methods in your libraries;
Example code from documentation page about interface having static and default methods.
import java.time.*;
public interface TimeClient {
void setTime(int hour, int minute, int second);
void setDate(int day, int month, int year);
void setDateAndTime(int day, int month, int year,
int hour, int minute, int second);
LocalDateTime getLocalDateTime();
static ZoneId getZoneId (String zoneString) {
try {
return ZoneId.of(zoneString);
} catch (DateTimeException e) {
System.err.println("Invalid time zone: " + zoneString +
"; using default time zone instead.");
return ZoneId.systemDefault();
}
}
default ZonedDateTime getZonedDateTime(String zoneString) {
return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
}
}
Use the below guidelines to chose whether to use an interface or abstract class.
Interface:
To define a contract ( preferably stateless - I mean no variables )
To link unrelated classes with has a capabilities.
To declare public constant variables (immutable state)
Abstract class:
Share code among several closely related classes. It establishes is a relation.
Share common state among related classes ( state can be modified in concrete classes)
Related posts:
Interface vs Abstract Class (general OO)
Implements vs extends: When to use? What's the difference?
By going through these examples, you can understand that
Unrelated classes can have capabilities through interface but related classes change the behaviour through extension of base classes.
Your explanation looks decent, but may be it looked like you were reading it all from a textbook? :-/
What I'm more bothered about is, how solid was your example? Did you bother to include almost all the differences between abstract and interfaces?
Personally, I would suggest this link:
http://mindprod.com/jgloss/interfacevsabstract.html#TABLE
for an exhaustive list of differences..
Hope it helps you and all other readers in their future interviews
Many junior developers make the mistake of thinking of interfaces, abstract and concrete classes as slight variations of the same thing, and choose one of them purely on technical grounds: Do I need multiple inheritance? Do I need some place to put common methods? Do I need to bother with something other than just a concrete class? This is wrong, and hidden in these questions is the main problem: "I". When you write code for yourself, by yourself, you rarely think of other present or future developers working on or with your code.
Interfaces and abstract classes, although apparently similar from a technical point of view, have completely different meanings and purposes.
Summary
An interface defines a contract that some implementation will fulfill for you.
An abstract class provides a default behavior that your implementation can reuse.
These two points above is what I'm looking for when interviewing, and is a compact enough summary. Read on for more details.
Alternative summary
An interface is for defining public APIs
An abstract class is for internal use, and for defining SPIs
By example
To put it differently: A concrete class does the actual work, in a very specific way. For example, an ArrayList uses a contiguous area of memory to store a list of objects in a compact manner which offers fast random access, iteration, and in-place changes, but is terrible at insertions, deletions, and occasionally even additions; meanwhile, a LinkedList uses double-linked nodes to store a list of objects, which instead offers fast iteration, in-place changes, and insertion/deletion/addition, but is terrible at random access. These two types of lists are optimized for different use cases, and it matters a lot how you're going to use them. When you're trying to squeeze performance out of a list that you're heavily interacting with, and when picking the type of list is up to you, you should carefully pick which one you're instantiating.
On the other hand, high level users of a list don't really care how it is actually implemented, and they should be insulated from these details. Let's imagine that Java didn't expose the List interface, but only had a concrete List class that's actually what LinkedList is right now. All Java developers would have tailored their code to fit the implementation details: avoid random access, add a cache to speed up access, or just reimplement ArrayList on their own, although it would be incompatible with all the other code that actually works with List only. That would be terrible... But now imagine that the Java masters actually realize that a linked list is terrible for most actual use cases, and decided to switch over to an array list for their only List class available. This would affect the performance of every Java program in the world, and people wouldn't be happy about it. And the main culprit is that implementation details were available, and the developers assumed that those details are a permanent contract that they can rely on. This is why it's important to hide implementation details, and only define an abstract contract. This is the purpose of an interface: define what kind of input a method accepts, and what kind of output is expected, without exposing all the guts that would tempt programmers to tweak their code to fit the internal details that might change with any future update.
An abstract class is in the middle between interfaces and concrete classes. It is supposed to help implementations share common or boring code. For example, AbstractCollection provides basic implementations for isEmpty based on size is 0, contains as iterate and compare, addAll as repeated add, and so on. This lets implementations focus on the crucial parts that differentiate between them: how to actually store and retrieve data.
Another perspective: APIs versus SPIs
Interfaces are low-cohesion gateways between different parts of code. They allow libraries to exist and evolve without breaking every library user when something changes internally. It's called Application Programming Interface, not Application Programming Classes. On a smaller scale, they also allow multiple developers to collaborate successfully on large scale projects, by separating different modules through well documented interfaces.
Abstract classes are high-cohesion helpers to be used when implementing an interface, assuming some level of implementation details. Alternatively, abstract classes are used for defining SPIs, Service Provider Interfaces.
The difference between an API and an SPI is subtle, but important: for an API, the focus is on who uses it, and for an SPI the focus is on who implements it.
Adding methods to an API is easy, all existing users of the API will still compile. Adding methods to an SPI is hard, since every service provider (concrete implementation) will have to implement the new methods. If interfaces are used to define an SPI, a provider will have to release a new version whenever the SPI contract changes. If abstract classes are used instead, new methods could either be defined in terms of existing abstract methods, or as empty throw not implemented exception stubs, which will at least allow an older version of a service implementation to still compile and run.
A note on Java 8 and default methods
Although Java 8 introduced default methods for interfaces, which makes the line between interfaces and abstract classes even blurrier, this wasn't so that implementations can reuse code, but to make it easier to change interfaces that serve both as an API and as an SPI (or are wrongly used for defining SPIs instead of abstract classes).
"Book knowledge"
The technical details provided in the OP's answer are considered "book knowledge" because this is usually the approach used in school and in most technology books about a language: what a thing is, not how to use it in practice, especially in large scale applications.
Here's an analogy: supposed the question was:
What is better to rent for prom night, a car or a hotel room?
The technical answer sounds like:
Well, in a car you can do it sooner, but in a hotel room you can do it more comfortably. On the other hand, the hotel room is in only one place, while in the car you can do it in more places, like, let's say you can go to the vista point for a nice view, or in a drive-in theater, or many other places, or even in more than one place. Also, the hotel room has a shower.
That is all true, but completely misses the points that they are two completely different things, and both can be used at the same time for different purposes, and the "doing it" aspect is not the most important thing about either of the two options. The answer lacks perspective, it shows an immature way of thinking, while correctly presenting true "facts".
An interface is a "contract" where the class that implements the contract promises to implement the methods. An example where I had to write an interface instead of a class was when I was upgrading a game from 2D to 3D. I had to create an interface to share classes between the 2D and the 3D version of the game.
package adventure;
import java.awt.*;
public interface Playable {
public void playSound(String s);
public Image loadPicture(String s);
}
Then I can implement the methods based on the environment, while still being able to call those methods from an object that doesn't know which version of the game that is loading.
public class Adventure extends JFrame implements Playable
public class Dungeon3D extends SimpleApplication implements Playable
public class Main extends SimpleApplication implements AnimEventListener,
ActionListener, Playable
Typically, in the gameworld, the world can be an abstract class that performs methods on the game:
public abstract class World...
public Playable owner;
public Playable getOwner() {
return owner;
}
public void setOwner(Playable owner) {
this.owner = owner;
}
What about thinking the following way:
A relationship between a class and an abstract class is of type "is-a"
A relationship between a class and an interface is of type "has-a"
So when you have an abstract class Mammals, a subclass Human, and an interface Driving, then you can say
each Human is-a Mammal
each Human has-a Driving (behavior)
My suggestion is that the book knowledge phrase indicates that he wanted to hear the semantic difference between both (like others here already suggested).
Abstract classes are not pure abstraction bcz its collection of concrete(implemented methods) as well as unimplemented methods.
But
Interfaces are pure abstraction bcz there are only unimplemented methods not concrete methods.
Why Abstract classes?
If user want write common functionality for all objects.
Abstract classes are best choice for reimplementation in future that to add more functionality without affecting of end user.
Why Interfaces?
If user want to write different functionality that would be different functionality on objects.
Interfaces are best choice that if not need to modify the requirements once interface has been published.
The main difference what i have observed was that abstract class provides us with some common behaviour implemented already and subclasses only needs to implement specific functionality corresponding to them. where as for an interface will only specify what tasks needs to be done and no implementations will be given by interface. I can say it specifies the contract between itself and implemented classes.
An interface is like a set of genes that are publicly documented to have some kind of effect: A DNA test will tell me whether I've got them - and if I do, I can publicly make it known that I'm a "carrier" and part of my behavior or state will conform to them. (But of course, I may have many other genes that provide traits outside this scope.)
An abstract class is like the dead ancestor of a single-sex species(*): She can't be brought to life but a living (i.e. non-abstract) descendant inherits all her genes.
(*) To stretch this metaphor, let's say all members of the species live to the same age. This means all ancestors of a dead ancestor must also be dead - and likewise, all descendants of a living ancestor must be alive.
I do interviews for work and i would look unfavourably on your answer aswell (sorry but im very honest). It does sound like you've read about the difference and revised an answer but perhaps you have never used it in practice.
A good explanation as to why you would use each can be far better than having a precise explanation of the difference. Employers ultimatley want programers to do things not know them which can be hard to demonstrate in an interview. The answer you gave would be good if applying for a technical or documentation based job but not a developers role.
Best of luck with interviews in the future.
Also my answer to this question is more about interview technique rather than the technical material youve provided. Perhaps consider reading about it. https://workplace.stackexchange.com/ can be an excellent place for this sort of thing.
In a few words, I would answer this way:
inheritance via class hierarchy implies a state inheritance;
whereas inheritance via interfaces stands for behavior inheritance;
Abstract classes can be treated as something between these two cases (it introduces some state but also obliges you to define a behavior), a fully-abstract class is an interface (this is a further development of classes consist from virtual methods only in C++ as far as I'm aware of its syntax).
Of course, starting from Java 8 things got slightly changed, but the idea is still the same.
I guess this is pretty enough for a typical Java interview, if you are not being interviewed to a compiler team.
An interface is purely abstract. we dont have any implementation code in interface.
Abstract class contains both methods and its implementation.
click here to watch tutorial on interfaces and abstract classes
Even I have faced the same question in multiple interviews and believe me it makes your time miserable to convince the interviewer.
If I inherent all the answers from above then I need to add one more key point to make it more convincing and utilizing OO at its best
In case you are not planning any modification in the rules , for the subclass to be followed, for a long future, go for the interface, as you wont be able to modify in it and if you do so, you need to go for the changes in all the other sub classes, whereas, if you think, you want to reuse the functionality, set some rules and also make it open for modification, go for Abstract class.
Think in this way, you had used a consumable service or you had provided some code to world and You have a chance to modify something, suppose a security check
And If I am being a consumer of the code and One morning after a update , I find all read marks in my Eclipse, entire application is down.
So to prevent such nightmares, use Abstract over Interfaces
I think this might convince the Interviewer to a extent...Happy Interviews Ahead.
When I am trying to share behavior between 2 closely related classes, I create an abstract class that holds the common behavior and serves as a parent to both classes.
When I am trying to define a Type, a list of methods that a user of my object can reliably call upon, then I create an interface.
For example, I would never create an abstract class with 1 concrete subclass because abstract classes are about sharing behavior. But I might very well create an interface with only one implementation. The user of my code won't know that there is only one implementation. Indeed, in a future release there may be several implementations, all of which are subclasses of some new abstract class that didn't even exist when I created the interface.
That might have seemed a bit too bookish too (though I have never seen it put that way anywhere that I recall). If the interviewer (or the OP) really wanted more of my personal experience on that, I would have been ready with anecdotes of an interface has evolved out of necessity and visa versa.
One more thing. Java 8 now allows you to put default code into an interface, further blurring the line between interfaces and abstract classes. But from what I have seen, that feature is overused even by the makers of the Java core libraries. That feature was added, and rightly so, to make it possible to extend an interface without creating binary incompatibility. But if you are making a brand new Type by defining an interface, then the interface should be JUST an interface. If you want to also provide common code, then by all means make a helper class (abstract or concrete). Don't be cluttering your interface from the start with functionality that you may want to change.
You choose Interface in Java to avoid the Diamond Problem in multiple inheritance.
If you want all of your methods to be implemented by your client you go for interface. It means you design the entire application at abstract.
You choose abstract class if you already know what is in common. For example Take an abstract class Car. At higher level you implement the common car methods like calculateRPM(). It is a common method and you let the client implement his own behavior like
calculateMaxSpeed() etc. Probably you would have explained by giving few real time examples which you have encountered in your day to day job.
To keep it down to a simple, reasonable response you can provide in an interview, I offer the following...
An interface is used to specify an API for a family of related classes - the relation being the interface. Typically used in a situation that has multiple implementations, the correct implementation being chosen either by configuration or at runtime. (Unless using Spring, at which point an interface is basically a Spring Bean). Interfaces are often used to solve the multiple inheritance issue.
An abstract class is a class designed specifically for inheritance. This also implies multiple implementations, with all implementations having some commonality (that found in the abstract class).
If you want to nail it, then say that an abstract class often implements a portion of an interface - job is yours!
The basic difference between interface and abstract class is, interface supports multiple inheritance but abstract class not.
In abstract class also you can provide all abstract methods like interface.
why abstract class is required?
In some scenarios, while processing user request, the abstract class doesn't know what user intention. In that scenario, we will define one abstract method in the class and ask the user who extending this class, please provide your intention in the abstract method. In this case abstract classes are very useful
Why interface is required?
Let's say, I have a work which I don't have experience in that area. Example,
if you want to construct a building or dam, then what you will do in that scenario?
you will identify what are your requirements and make a contract with that requirements.
Then call the Tenders to construct your project
Who ever construct the project, that should satisfy your requirements. But the construction logic is different from one vendor to other vendor.
Here I don't bother about the logic how they constructed. The final object satisfied my requirements or not, that only my key point.
Here your requirements called interface and constructors are called implementor.
hmm now the people are hungery practical approach, you are quite right but most of interviewer looks as per their current requirment and want a practical approach.
after finishing your answer you should jump on the example:
Abstract:
for example we have salary function which have some parametar common to all employee. then we can have a abstract class called CTC with partialy defined method body and it will got extends by all type of employee and get redeined as per their extra beefits.
For common functonality.
public abstract class CTC {
public int salary(int hra, int da, int extra)
{
int total;
total = hra+da+extra;
//incentive for specific performing employee
//total = hra+da+extra+incentive;
return total;
}
}
class Manger extends CTC
{
}
class CEO extends CTC
{
}
class Developer extends CTC
{
}
Interface
interface in java allow to have interfcae functionality without extending that one and you have to be clear with the implementation of signature of functionality that you want to introduce in your application. it will force you to have definiton.
For different functionality.
public interface EmployeType {
public String typeOfEmployee();
}
class ContarctOne implements EmployeType
{
#Override
public String typeOfEmployee() {
return "contract";
}
}
class PermanentOne implements EmployeType
{
#Override
public String typeOfEmployee() {
return "permanent";
}
}
you can have such forced activity with abstract class too by defined methgos as a abstract one, now a class tha extends abstract class remin abstract one untill it override that abstract function.
From what I understand, an Interface, which is comprised of final variables and methods with no implementations, is implemented by a class to obtain a group of methods or methods that are related to each other. On the other hand, an abstract class, which can contain non-final variables and methods with implementations, is usually used as a guide or as a superclass from which all related or similar classes inherits from. In other words, an abstract class contains all the methods/variables that are shared by all its subclasses.
In abstract class, you can write default implementation of methods! But in Interface you can not. Basically, In interface there exist pure virtual methods which have to be implemented by the class which implements the interface.
Yes, your responses were technically correct but where you went wrong was not showing them you understand the upsides and downsides of choosing one over the other. Additionally, they were probably concerned/freaked out about compatibility of their codebase with upgrades in the future. This type of response may have helped (in addition to what you said):
"Choosing an Abstract Class over an Interface Class depends on what we
project the future of the code will be.
Abstract classes allow better forward-compatibility because you can
continue adding behavior to an Abstract Class well into the future
without breaking your existing code --> this is not possible with an
Interface Class.
On the other hand, Interface Classes are more flexible than Abstract
Classes. This is because they can implement multiple interfaces. The
thing is Java does not have multiple inheritances so using abstract
classes won't let you use any other class hierarchy structure...
So, in the end a good general rule of thumb is: Prefer using Interface
Classes when there are no existing/default implementations in your
codebase. And, use Abstract Classes to preserve compatibility if you
know you will be updating your class in the future."
Good luck on your next interview!
I will try to answer using practical scenario to show the distinction between the two.
Interfaces come with zero payload i.e. no state has to be maintained and thus are better choice to just associate a contract (capability) with a class.
For example, say I have a Task class that performs some action, now to execute a task in separate thread I don't really need to extend Thread class rather better choice is to make Task implement Runnable interface (i.e. implement its run() method) and then pass object of this Task class to a Thread instance and call its start() method.
Now you can ask what if Runnable was a abstract class?
Well technically that was possible but design wise that would have been a poor choice reason being:
Runnable has no state associated with it and neither it 'offers' any
default implementation for the run() method
Task would have to extend it thus it couldn't extend any other class
Task has nothing to offer as specialization to Runnable class, all it needs is to override run() method
In other words, Task class needed a capability to be run in a thread which it achieved by implementing Runnable interface verses extending the Thread class that would make it a thread.
Simply put us interface to define a capability (contract), while use a
abstract class to define skeleton (common/partial) implementation of
it.
Disclaimer: silly example follows, try not to judge :-P
interface Forgiver {
void forgive();
}
abstract class GodLike implements Forgiver {
abstract void forget();
final void forgive() {
forget();
}
}
Now you have been given a choice to be GodLike but you may choose to be Forgiver only (i.e. not GodLike) and do:
class HumanLike implements Forgiver {
void forgive() {
// forgive but remember
}
}
Or you may may choose to be GodLike and do:
class AngelLike extends GodLike {
void forget() {
// forget to forgive
}
}
P.S. with java 8 interface can also have static as well default (overridable implementation) methods and thus difference b/w interface and abstract class is even more narrowed down.
Almost everything seems to be covered here already.. Adding just one more point on practical implementation of abstract class:
abstract keyword is also used just prevent a class from being instantiated. If you have a concrete class which you do not want to be instantiated - Make it abstract.
From what I understand and how I approach,
Interface is like a specification/contract, any class that implements an interface class have to implement all the methods defined in the abstract class (except default methods (introduced in Java 8))
Whereas I define a class abstract when I know the implementation required for some methods of the class and some methods I still do not know what will be the implementation (we might know the function signature but not the implementation). I do this so that later in the part of development when I know how these methods are to be implemented, I can just extend this abstract class and implement these methods.
Note: You cannot have function body in interface methods unless the method is static or default.
Here’s an explanation centred around Java 8, that tries to show the key differences between abstract classes and interfaces, and cover all the details needed for the Java Associate Exam.
Key concepts:
A class can extend only one class, but it can implement any number of interfaces
Interfaces define what a class does, abstract classes define what it is
Abstract classes are classes. They can’t be instantiated, but otherwise behave like normal classes
Both can have abstract methods and static methods
Interfaces can have default methods & static final constants, and can extend other interfaces
All interface members are public (until Java 9)
Interfaces define what a class does, abstract classes define what it is
Per Roedy Green:
Interfaces are often used to describe the abilities of a class, not its central identity, e.g. An Automobile class might implement the Recyclable interface, which could apply to many unrelated objects. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Dalmatian descendants are Dogs, they are not merely dogable.
Pre Java 8, #Daniel Lerps’s answer was spot on, that interfaces are like a contract that the implementing class has to fulfil.
Now, with default methods, they are more like a Mixin, that still enforces a contract, but can also give code to do the work. This has allowed interfaces to take over some of the use cases of abstract classes.
The point of an abstract class is that it has missing functionality, in the form of abstract methods. If a class doesn’t have any abstract behaviour (which changes between different types) then it could be a concrete class instead.
Abstract classes are classes
Here are some of the normal features of classes which are available in abstract classes, but not in interfaces:
Instance variables / non-final variables. And therefore…
Methods which can access and modify the state of the object
Private / protected members (but see note on Java 9)
Ability to extend abstract or concrete classes
Constructors
Points to note about abstract classes:
They cannot be final (because their whole purpose is to be extended)
An abstract class that extends another abstract class inherits all of its abstract methods as its own abstract methods
Abstract methods
Both abstract classes and interfaces can have zero to many abstract methods. Abstract methods:
Are method signatures without a body (i.e. no {})
Must be marked with the abstract keyword in abstract classes. In interfaces this keyword is unnecessary
Cannot be private (because they need to be implemented by another class)
Cannot be final (because they don’t have bodies yet)
Cannot be static (because reasons)
Note also that:
Abstract methods can be called by non-abstract methods in the same class/interface
The first concrete class that extends an abstract class or implements an interface must provide an implementation for all the abstract methods
Static methods
A static method on an abstract class can be called directly with MyAbstractClass.method(); (i.e. just like for a normal class, and it can also be called via a class that extends the abstract class).
Interfaces can also have static methods. These can only be called via the name of the interface (MyInterface.method();). These methods:
Cannot be abstract, i.e. must have a body (see ‘because reasons’ above)
Are not default (see below)
Default methods
Interfaces can have default methods which must have the default keyword and a method body. These can only reference other interface methods (and can’t refer to a particular implementation's state). These methods:
Are not static
Are not abstract (they have a body)
Cannot be final (the name “default” indicates that they may be overridden)
If a class implements two interfaces with default methods with the same signatures this causes a compilation error, which can be resolved by overriding the method.
Interfaces can have static final constants
Interfaces can only contain the types of methods describe above, or constants.
Constants are assumed to be static and final, and can be used without qualification in classes that implement the interface.
All interface members are public
In Java 8 all members of interfaces (and interfaces themselves) are assumed to be public, and cannot be protected or private (but Java 9 does allow private methods in interfaces).
This means that classes implementing an interface must define the methods with public visibility (in line with the normal rule that a method cannot be overridden with lower visibility).
I believe what the interviewer was trying to get at was probably the difference between interface and implementation.
The interface - not a Java interface, but "interface" in more general terms - to a code module is, basically, the contract made with client code that uses the interface.
The implementation of a code module is the internal code that makes the module work. Often you can implement a particular interface in more than one different way, and even change the implementation without client code even being aware of the change.
A Java interface should only be used as an interface in the above generic sense, to define how the class behaves for the benefit of client code using the class, without specifying any implementation. Thus, an interface includes method signatures - the names, return types, and argument lists - for methods expected to be called by client code, and in principle should have plenty of Javadoc for each method describing what that method does. The most compelling reason for using an interface is if you plan to have multiple different implementations of the interface, perhaps selecting an implementation depending on deployment configuration.
A Java abstract class, in contrast, provides a partial implementation of the class, rather than having a primary purpose of specifying an interface. It should be used when multiple classes share code, but when the subclasses are also expected to provide part of the implementation. This permits the shared code to appear in only one place - the abstract class - while making it clear that parts of the implementation are not present in the abstract class and are expected to be provided by subclasses.

Can I create a non-abstract method in an interface that will be called by every implementation? [duplicate]

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.

Serialization not implemented?

What I understand is that I can implement Serializable interface to make my object serializable.
But I don't get where is writeObject method implemented when Serializable is an interface, so it doesn't contain implementation of methods, just a definition?
As you already noticed, the Serializable is a Marker Interface and does not have any methods to implement. Implementing Serializable is just a note that this one is eligible for serialization which is handled using ObjectOutputStream.
Methods you mentioned need to be implemented in a class implementing the Serializable interface and will be picked up automatically. Since there is no obligation for implementing them, they are not included in the interface.
http://docs.oracle.com/javase/8/docs/platform/serialization/spec/serial-arch.html#a4539
Tough all the answers posted so far are right, I wish to add some extra comments:
java.io.Serializable was already part of the Java 1.1 API (among the first versions of Java), and was meant as an easy way for the programmer to mark any class to have a special behaviour.
According to OOP principles, that should have been done through a regular interface, which is what you (and me, and any other programmer) would have expected. Something like this:
public interface Serializable<E>
{
public E read(DataInput input) throws IOException;
public void write(DataOutput output) throws IOException;
}
But, since there are many classes in Java which needed to be serialized, the Java Language designers wished to save troubles to programmers, by some kind of mechanism through which serialization would be performed automatically. But how?
Through an abstract class? Nope. That would have prevented any custom class to have its own hierarchy (since in Java there is only single inheritance).
Making java.lang.Object serializable? Neither so, because that would have prevented programmers to decide which class should be serializable and which should not.
On top of all, there was a hughe problem: Note that method read is supposed to create and return an object of class E from a DataInput stream. An abstract class just can not create instances of its subclasses whithout further information (the abstract class does not know which is the applied subclass).
So, they decided to pass over the OOP and offer Serialization as a special non-oop feature of the serialization classes ObjectOutputStream/ObjectInputStream (credits to EJP for this detail) in the form of a "dummy" interface recognizable by them, at the price of adding somehow some confussion to the class definitions, because an interface with no methods is nonsense (Same approach they adopted for java.lang.Cloneable).
Actually, it adds even more confussion, because custom serialization must be done by implementing private methods readObject and writeObject (as specified by ObjectOutputStream), which is a feature non describible in terms of a Java interface.
Nowadays, these kind of marking can be done through annotations. Well, think of Serializable as an interface which should have been an annotation, but still remains as an interface for those -endless- compatibility reasons.

API design: one generic interface VS three specialized interfaces?

I'm working on a tool where users can use their own annotations to describe data processing workflow (like validation, transformation etc).
Besides using ready-to-use annotations, users can user their own: in order to do this they need to declare annotation class itself, and then implement annotation processor (<--it's the main point of this question actualy).
The configured method for data processing may look like this one:
void foo(#Provide("dataId") #Validate(Validator.class) String str) {
doSmth(str);
}
There're naturally three groups of annotations:
those which produce initial values;
those which transforms values (converters);
those which just read values and perform some work (validators, different consumers).
So I need to make a choise: either create one interface for handling all these types of annotations, which can look like this one:
interface GenericAnnotationProcessor {
Object processAnnotation(Annotation annotation, Object processedValue);
}
Or I can add 3 intefaces to the API:
interface ProducerAnnotationProcessor {
Object produceInitValue(Annotation annotation);
}
interface TransformerAnnotationProcessor {
Object transformValue(Annotation annotation, Object currentValue);
}
interface ConsumerAnnotationProcessor {
void consumeValue(Annotation annotation, Object currentValue);
}
The first option is not very clear in use, but the third option pollutes the API with 3 almost similar interfaces.
What would you choose (first of all as an API user) and why?
Thanks!
I would create the first, more general interface, then define the three different implementation classes. Without knowing more about how you will be using this, my first instinct would be to define the Interface and/or a base class (depending upon how much common implementation code was shared between the different processors), and then add specialized processor implementation in derived types, all of whihc share the common interface.
In using the API, I would expect to declare a variable which implements GenericAnnotationProcessor, and then assign the appropriate implementation type depending upon my needs.
It is early here in Portland, OR, but at this moment, at 50% of my required caffeine level, this seems to me like it would provide maximum flexibility while maximizing cade re-use.
Of course, your actual reuirements might dictate otherwise . . .
Hope that was helpful!
Just diving deep into your problem.
As they are executing similar task, with some variance, Strategy pattern #Example should assist you.
Your problem should look like something below.
interface GenericAnnotationProcessor {
Object processAnnotation(Annotation annotation, Object processedValue);
}
interface ProducerAnnotationProcessor implements GenericAnnotationProcessor {
}
interface TransformerAnnotationProcessor implements GenericAnnotationProcessor {
}
interface ConsumerAnnotationProcessor implements GenericAnnotationProcessor {
}
Now you can follow example from Wiki
class Context {
// map of annotation processors
// register(add/remove) annotation processors to the map
public int executeAnnotationProcessor(Annotation annotation, Object processedValue) {
return locateAnnotationProcessor(annotation).processAnnotation(annotation, processedValue);
}
private GenericAnnotationProcessor locateAnnotationProcessor(Annotation annotation) {
// return expected annotation processor
}
}
I believe you can understand.
You can use Interfaces Extending Interfaces More on there
Similar to classes, you can build up inheritance hierarchies of interfaces by using the extends keyword, as in:
interface Washable {
void wash();
}
interface Soakable extends Washable {
void soak();
}
In this example, interface Soakable extends interface Washable. Consequently, Soakable inherits all the members of Washable. A class that implements Soakable must provide bodies for all the methods declared in or inherited by Soakable, wash() and soak(), or be declared abstract. Note that only interfaces can "extend" other interfaces. Classes can't extend interfaces, they can only implement interfaces.
Hope it helps.

When to use extends and when to use interface?

We can extend a class but we cannot implement a class. We can implement an interface, but cannot extend an interface.
In what cases should we be using extends?
extends is used for either extending a base class:
class ClassX extends ClassY {
...
}
or extending an interface:
interface InterfaceA extends InterfaceB {
...
}
Note that interfaces cannot implement other interfaces (most likely because they have no implementation).
Java doesn't impose any naming conventions for classes vs. interfaces (in contrast to IFoo for interfaces in the .NET world) and instead uses the difference between extends and implements to signify the difference to the programmer:
class ClassA extends ClassB implements InterfaceC, InterfaceD {
...
}
Here you can clearly see that you're building upon an existing implementation in ClassB and also implement the methods from two interfaces.
Is a matter of uses. Interfaces can be used as a contract with your application and then base classes can be use to extend that interface, so it is loosely couple.
Take for example Injection Dependency pattern:
You first write a contract:
public interface IProductRepository
{
IList<T> GetAllProducts();
}
Then you extend your contract with a base class:
public abstract BaseProductRepository : IProductRepository
{
public IList<T> GetAllProducts()
{ //Implementation }
}
Now you have the option to extend base into two or more concrete classes:
public class InternetProductRepository extends BaseProductRepository;
public class StoreProductRepository extends BaseProductRepository;
I hope this small examples clears the differences between extend and Implement. sorry that I did not use java for the example but is all OO, so I think you will get the point.
Thanks for reading, Geo
I did not complete the code for injection dependency pattern but the idea is there, is also well documented on the net. Let me know if you have any questions.
Actually, you can extend an interface - in the case where you're defining another interface.
There are lots of quasi-religious arguments about this issue and I doubt there's a clear right answer, but for what it's worth here's my take on things. Use subclassing (i.e. extends), when your various classes provide the same sort of functionality, and have some implementation details in common. Use interface implementation, in order to signal that your classes provide some particular functionality (as specified by the interface).
Note that the two are not mutually exclusive; in fact if a superclass implements an interface, then any subclasses will also be considered to implement that interface.
In Java there is no multiple inheritance, so that a (sub)class can only have one parent class, and subclassing should be considered carefully so as to choose an appropriate parent if any at all; choosing a parent that reflects just a small amount of the class' abilities is likely to end in frustration later if there are other sensible parent classes. So for example, having an AbstractSQLExecutor with SQL Server and Oracle subclasses makes a lot of sense; but having a FileUtils parent class with some utility methods in, and then subclassing that all over the place in order to inherit that functionality, is a bad idea (in this case you should likely declare the helper methods static, or hold a reference to a FileUtils instance, instead).
Additionally, subclassing ties you to implementation details (of your parent) more than implementing an interface does. I'd say that in general it's better merely to implement the interface, at least initially, and only form class hierarchies of classes in the same or similar packages with a clear hierarchical structure.
Like you said. the implement java keyword is used to implement an interface where the extends is used to extend a class.
It depends what you would like to do. Typically you would use an interface when you want to force implementation (like a contract). Similar to an abstract class (but with an abstract class you can have non-abstract methods).
Remember in java you can only extend one class and implement zero to many interfaces for the implementing class. Unlike C# where you can extend multiple classes using :, and where C# only uses the : symbol for both interfaces and classes.
extends keyword is used for either extending a concrete/abstract class. By extending, u can either override methods of parent class / inherit them. A class can only extend class.
U can also say interface1 extends intenface2.
implements keyword is used for implementing interface. In this case u have to define all the methods indicated in interface. A class can only implement interface.

Categories