Why interface methods have no body - java

To achieve multiple inheritance, we must use interfaces, but why don't interface methods have bodies and why do they have to be overridden in the derived class?
I really want a lucid answer , not involving too much computer jargon , i cant seem to understand this , i have referred various references

Because Java, in contrast to languages like C++ or Eiffel, only has multiple inheritance of types (i.e. interfaces as well as one class), not multiple inheritance of state and behaviour. The latter of which add enormous complexity (especially state).
The Java designers (and C#, for that matter) opted to not include it as it presented C++ programmers often with very hard to debug issues. You can solve pretty much most problems that require true multiple inheritance with implementing multiple interfaces, so the tradeoff was deemed worth it.
Note that multiple inheritance of behaviour (not state) might come to Java 8 (unless they postpone it again like one of the many other things) in form of virtual extension methods where an interface can declare a method that delegates to one in another class, which then exists on all types that implement that interface.

Interfaces declare WHAT services the implementing class provides, not HOW (that's the job of the implementing class). Multiple inheritance is regarded bad, as it leads to complicated code and class hierarchies.

Interfaces only have constant variables(public + static + final) and abstract methods(public & abstract). These are meant to be used by the classes which implement the interfaces.
Interfaces simply say 'Am a contract', which if you wish to use, should stick to some rules(give implementation to all abstract methods).
Multiple inheritance is omitted in Java by making sure that a class can extend only 1 class, in order to avoid the diamond problem. You can anyways have multiple inheritance of types in Java by using interfaces.

A Java interface contains a list of methods that must be implemented by the class that implements the interface. Thus, the methods have no body: the body of each method is in the implementing class(es).

Simple Answer:
An interface provides a standard for implementation.
Explanation:
In Java an interface is similar to an abstract class in that its members are not implemented. For example,
public interface Comparable
{ boolean less(Object m);
boolean greater(Object m);
boolean lessEqual(Object m);
boolean greaterEqual(Object m);
}
An interface provides a standard for implementation.
Benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed in java.
All instance methods are implicitly public and abstract. You can mark them as such, but are discouraged from doing so as the marking is considered obsolete practice. The interfaces themselves need not be public and several interfaces in the standard libraries are not public and thus used only internally.
An interface creates a protocol that classes may implement. Note that one can extend an interface (to get a new interface) just as you can extend a class. One can actually extend several interfaces. Interfaces thus enjoy the benefits of multiple inheritance. (Classes do not.) There are almost no disadvantages to multiple inheritance of interface (small name conflict problems are one exception). There are large disadvantages to multiple inheritance of implementation as in C++. These include efficiency considerations as well as the semantic difficulty of determining just what code will be executed in some circumstances.
The Polynomial class that implements Comparable will need to implement all of the functions declared in the interface.
public class Polynomial implements Comparable
{ . . .
boolean less(Object m){ . . . }
boolean greater(Object m){ . . . }
boolean lessEqual(Object m){ . . . }
boolean greaterEqual(Object m){ . . . }
Polynomial multiply(Polynomial P){ . . . }
. . .
}
A class may choose to implement any number of interfaces. A class that implements an interface must provide bodies for all methods of that interface. Also, We expect that an abstract class can choose to implement part of an interface leaving the rest for non-abstract subclasses.
The usefulness of interfaces goes far beyond simply publishing protocols for other programmers. Any function can have parameters that are of interface type. Any object from a class that implements the interface may be passed as an argument.
References:
Interface
Interfaces
Interface Wiki

Interface methods has no body
like
public interface Flyable
{
public void fly();
}
because interface itself not going to do anything
interface is defines contract.
an interface, on other hand, defines what a class can do,
not what it is. So interface is about verbs usually.
So the Flyable interface is doing nothing but defines the contract that the implanted
FlyableObjects are going to fly.
like:
class Rocket implements Flyable
{
public void fly()
{
// do the stuffs.
}
}
interface
and ofcourse we can achieve multiple inheritance also only and only through interface.

if interfaces had bodies then it would have brought back the Deadly Daimond of Death problem.
Consider this example having interfaces with bodies
interface A {
void print(){ System.out.print("A") }
}
interface B {
void print(){ System.out.print("B") }
}
interface C extends A, B {
// now since A and B have bodies interfaces would have had choice to not to override the default behavior
}
public class C_Implementer implements C{
public static void main(String args[]){
C c = new C_Implementer();
c.print(); // gotcha!!!!! what should it print, A or B????
}
}

You are asking "Why does Java not support multiple inheritance of implementation?"
This is discussed in the Java Tutorials, Multiple Inheritance of State, Implementation, and Type, but I wanted to give a specific example of the problems of multiple inheritance of implementation (as well as a new language feature solution at the end).
Imagine two interfaces (in our proposed version of Java that allows interface method bodies) that define a method with the same name.
public interface FaceOne {
public void method() {
System.out.println("FaceOne Version");
}
}
public interface FaceTwo {
public void method() {
System.out.println("FaceTwo Version");
}
}
And a class implements both interfaces, but doesn't override the method.
public class Inheriter implements FaceOne, FaceTwo {
}
When I call Inheriter.method(), which works since the class inherits the method from its ancestors, the problem arises: does the output print "FaceOne Version" or "FaceTwo Version"?
In addition, if the class were to override the method, but wanted to also call its ancestor's version using super, the compiler would again have trouble choosing between a version of the method.
This is why Java does not support multiple inheritance of implementation.
As an aside, I think an elegant way to implement this into the language would be as follows:
Continue to force implementing classes to override their ancestor interface's methods. This solves the first problem of a non-overridden method.
Then, use a similar notation as that of accessing an enclosing instance for an inner class to access a specific ancestor interface with super. The Inheriter class would then have multiple options:
Do not call super.method(), but rather only use newly-defined implementation.
Use FaceOne.super.method() to make the default inherited implementation output "FaceOne Version".
Use FaceTwo.super.method() to make the default inherited implementation output "FaceTwo Version".
Use a combination of the above:
One implementation could be:
#Override
public void method() {
FaceOne.super.method();
FaceTwo.super.method();
System.out.println("Inheriter Version");
}
Outputting:
FaceOne Version
FaceTwo Version
Inheriter Version
Edit: According to this question this is apparently exactly how default implementations are structured in Java 8.

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 interfaces evolve with time?

Interfaces are great from a flexibility standpoint. But in case, where an interface is used by a large number of clients. Adding new methods to the interface while keeping the old mehtods intact will break all clients' code as new methods won't be present in clients. As shown below:
public interface CustomInterface {
public void method1();
}
public class CustomImplementation implements CustomInterface {
#Override
public void method1() {
System.out.println("This is method1");
}
}
If at some point later in time, we add another method to this interface all clients' code will break.
public interface CustomInterface {
public void method1();
public void method2();
}
To avoid this we have to explicitly implement new methods in all clients' code.
So I think of interfaces and this scenario as following:
Interfaces once written are like carving in stone. They are rarely supposed, and expected to change. And if they do, they come with a huge cost(rewriting the whole code) which programmers should be ready for.
In continuation with the point above, Is it possible to write interfaces that can stand the test of time?
How such a scenario is handled in interfaces where you expect additional functionality in future? That is anticipating change in the contract by which all clients are binded.
EDIT: Default method is indeed a nice addition to Java Interfaces which a lot of people have mentioned in their answers. But my question was more in the context of code design. And how forcing method implementation on the client is an intrinsic character of an interface. But this contract between an interface and a client seems fragile as functionality will eventually evolve.
One solution to this problem was introduced in Java 8 in the form of default methods in interfaces. It allowed to add new methods to existing Java SE interfaces without breaking existing code, since it supplied default implementation to all the new methods.
For example, the Iterable interface, which is widely used (it's a super interface of the Collection interface) was added two new default methods - default void forEach(Consumer<? super T> action) and default Spliterator<T> spliterator().
public interface CustomInterface {
public void method1();
}
public interface CustomInterface2 extends CustomInterface {
public void meathod2();
}
Other than default method you can use inheritance property as show above by which new interface will have all previous method along with new methods and use this interface in your required situation.
Java 8 has introduced default implementation for methods. These implementations reside in the interface. If a new method with a default implementation is created in an interface that is already implemented by many classes, there is no need to modify all the classes, but only the ones that we want to have a different implementation for the newly defined method than the default one.
Now, what about older Java versions? Here we can have another interface that extends the first one. After that, classes that we want to implement the newly-declared method will be changed to implement the new interface. As shown below.
public interface IFirst {
void method1();
}
public class ClassOne implements IFirst() {
public void method1();
}
public class ClassTwo implements IFirst() {
public void method1();
}
Now, we want method2() declared, but it should only be implemented by ClassOne.
public interface ISecond extends iFirst {
void method2();
}
public class ClassOne implements ISecond() {
public void method1();
public void method2();
}
public class ClassTwo implements IFirst() {
public void method1();
}
This approach will be ok in most cases, but it does have downsides as well. For example, we want method3() (and only that one) for ClassTwo. We will need a new interface IThird. If later we will want to add method4() that should be implemented by both ClassOne and ClassTwo, we will need to modify (but not ClassThree that also implemented IFirst) we will need to change both ISecond and IThird.
There rarely is a "magic bullet" when it comes to programming. In the case of interfaces, it is best if they don't change. This isn't always the case in real-life situations. That is why it is advised that interfaces offer just "the contract" (must-have functionality) and when possible use abstract classes.
A future interface change shouldn't break anything that has been working -- if it does, it's a different interface. (It may deprecate things, though, and a full cycle after deprecation it may be acceptable to say that throwing an Unimplemented exception is acceptable.)
To add things to an interface, the cleanest answer is to derive a new interface from it. That will allow using objects implementing the new behaviors with code expecting the old ones, while letting the user declare appropriately and/or typecast to get access to the new features. It's a bit annoying since it may require instanceof tests, but it's the most robust approach, and it's the one you'll see in many industry standards.
Interfaces are contracts between the developer and clients, so you're right - they are carved in stone and should not be changed. Therefore, an interface should expose (= demand) only the basic functionality that's absolutely required from a class.
Take the List interface for example. There are many implementations of lists in Java, many of which evolve over time (better under-the-hood algorithms, improved memory storage), but the basic "concept" of a list - add an item, search for an item, remove an item - should not and will not ever change.
So, to your question: Instead of writing interfaces which classes implement, you can use abstract classes. Interfaces are basically purely-abstract classes, in the sense that they do not provide any built-in functionality. However, one can add new, non-abstract methods to an abstract class that clients will not be required to implement (override).
Take this abstract class (= interface) for example:
abstract class BaseQueue {
abstract public Object pop();
abstract public void push(Object o);
abstract public int length();
public void clearEven() {};
}
public class MyQueue extends BaseQueue {
#Override
public Object pop() { ... }
...
}
Just like in interfaces, every class that extends BaseQueue is contractually bound to implement the abstract methods. The clearEven() method, however, is not an abstract method (and already comes with an empty implementation), so the client is not forced to implement it, or even use it.
That means that you can leverage the power of abstract classes in Java in order to create non-contractually-binding methods. You can add other methods to the base class in the future as much as you like, provided that they are not abstract methods.
I think your question is more about design and techniques, so java8 answers are a bit misleading. This problem was known long before java8, so there are some other solutions for it.
First, there are no absolutely chargeless ways to solve a problem. The size of inconviniences that come from interface evolving depends on how the library is used and how deliberate your design is.
1) No techniques will help, if you designed an interface and forgot to include a mandatory method in it. Plan your design better and try to anticipate how clients will use your interfaces.
Example: Imagine Machine interface that has turnOn() method but misses turnOff() method. Introducing a new method with default empty implementation in java8 will prevent compilation errors but will not really help, because calling a method will have no effect. Providing working implementation is sometimes impossible because interface has no fields and state.
2) Different implementations usually have things in common. Don't be afraid to keep common logic in parent class. Inherit your library classes from this parent class. This will enforce library clients to inherit their own implementations from your parent class as well. Now you can make small changes to the interface without breaking everything.
Example: You decided to include isTurnedOn() method to your interface. With a basic class, you can write a default method implementation that would make sence. Classes that were not inherited from parent class still need to provide their own method implementations, but since method is not mandatory, it will be easy for them.
3) Upgrading the functionality is usually achieved by extending the interfaces. There's no reason to force library clients to implement a bunch of new methods because they may not need them.
Example: You decided to add stayIdle() method to your interface. It makes sence for classes in your library, but not for custom client classes. Since this functionality is new, it's better to create a new interface that will extend Machine and use it when it's needed.

what is the advantage of interface over abstract classes?

In Java, abstract classes give the ability to define both concrete and abstract methods whereas interfaces only give the ability to implement abstract methods.
I believe overriding methods in subclasses/implementations is possible in both cases, therefore, what is the real advantage of one over the other (interfaces vs abstract classes in Java)?
Interfaces are for when you want to say "I don't care how you do it, but here's what you need to get done."
Abstract classes are for when you want to say "I know what you should do, and I know how you should do it in some/many of the cases."
Abstract classes have some serious drawbacks. For example:
class House {
}
class Boat {
}
class HouseBoat extends /* Uh oh!! */ {
// don't get me started on Farmer's Insurance "Autoboathome" which is also a helicopter
}
You can get through via an interface:
interface Liveable {
}
interface Floatable {
}
class HouseBoat implements Liveable, Floatable {
}
Now, abstract classes are also very useful. For example, consider the AbstractCollection class. It defines the default behavior for very common methods to all Collections, like isEmpty() and contains(Object). You can override these behaviors if you want to, but... is the behavior for determining if a collection is empty really likely to change? Typically it's going to be size == 0. (But it can make a big difference! Sometimes size is expensive to calculate, but determining whether something is empty or not is as easy as looking at the first element.)
And since it won't change often, is it really worth the developer's time to implement that method every... single... time... for every method in that "solved" category? Not to mention when you need to make a change to it, you're going to have code duplication and missed bugs if you had to re-implement it everywhere.
Interfaces are useful because Java doesn't have multiple inheritance (but you can implement as many interfaces as you like).
Abstract classes are useful when you need concrete behaviour from the base class.
The facts are-
Java doesn't support multiple inheritance
Multiple interfaces can be implemented
Few methods in an abstract class may be implemented
These facts can be used to tilt the advantage in favor of interfaces or abstract classes.
If there are more than one behavior that a class must share with other classes, interfaces win.
If a method definition has to be shared/ overridden with other classes, abstract classes win.
An class may implement several interfaces, whereas it may only extend one class (abstract or concrete), because Java does not support multiple inheritance.
In OOP (mostly independent of a concrete language) abstract classes are a re-use mechanism for the class hierarchy for behaviour and structure which isn't complete on its own.
Interfaces are mechanism for specification of requirements on a module (e.g. class) independently of the concrete implementation.
All other differences are technical details, important is different usage.
You dont override an interface. You implement it.
Writing an interface gives implementors the ability to implement your interface and also other interfaces in addition to inheriting from a base class.
Abstract classes can be partially or fully implemented.Marking a class abstract just prevents you from instantiating an object of that type.
-Method without any implementation is abstract method,whenever a class contains one or more abstract method,then it must be declared as a abstract class
-Interface is fully abstract which cannot have constructor,instance and static blocks,and it contains only two types of members
1.public abstract method
2.public-static-final variable
*Both cannot be instantiated but reference can be created.
*Which one suits better depends on the application
-Interfaces are useful because Java classes will not support multiple inheritance but interfaces do.
-Abstract classes are useful when you need concrete behavior from the base class.
The main advantages of interface over abstract class is to overcome the occurrence of diamond
problem and achieve multiple inheritance.
In java there is no solution provided for diamond problem using classes.For this reason multiple inheritance is block using classes in java.
So to achieve multiple inheritance we use interface .
class Animal
{ void move(){} }
class Bird
{ void move(){fly} }
class Fish
{ void move(){swim} }
Now, if class Animal is abstract class like
Animal a;
a= new Bird(); or a = new Fish()
Here, abstraction works well, but if there are 100 objects like Animal a[100];
You can not write new Bird().move or new Fish().move 100 times
Use interface and write a[i].move. It will differentiate as bird or fish and that move() will be invoked
Second it supports multiple inheritance as class A can implements as many interfaces.
Amazing answers!!
I too want to put my opinion on Interface.
As the name says it is interface which means it will provide interface between two classes.
It help a class or interface hold multiple behavior at the same time.
Who ever having the interface can access the behavior of the class agreed with the interface.
interface teacher
{
//methods related to teacher
}
interface student
{
//methods related to student
}
interface employee
{
//methods related to employee
}
class Person:teacher,student,employee
{
//definition of all the methods in teacher,student, employee interface
//and method for person
}
Now here which ever class is having teacher interface will have access to only teacher behavior of Person.
Similarly the class or module having student interface will have access to only student behavior of person.
Using abstract class, it is not at all possible.
Hope this will add some additional points. :)
Happy coding!!.

How do Java Interfaces simulate multiple inheritance?

I am reading "The Java Tutorial" (for the 2nd time). I just got through the section on Interfaces (again), but still do not understand how Java Interfaces simulate multiple inheritance. Is there a clearer explanation than what is in the book?
Suppose you have 2 kinds of things in your domain : Trucks and Kitchens
Trucks have a driveTo() method and Kitchens a cook() method.
Now suppose Pauli decides to sell pizzas from the back of a delivery truck. He wants a thing where he can driveTo() and cook() with.
In C++ he would use multiple inheritance to do this.
In Java that was considered to be too dangerous so you can inherit from a main class, but you can "inherit" behaviors from interfaces, which are for all intents and purposes abstract classes with no fields or method implementations.
So in Java we tend to implement multiple inheritance using delegations :
Pauli subclasses a truck and adds a kitchen to the truck in a member variable called kitchen. He implements the Kitchen interface by calling kitchen.cook().
class PizzaTruck extends Truck implements Kitchen {
Kitchen kitchen;
public void cook(Food foodItem) {
kitchen.cook(foodItem);
}
}
He is a happy man because he can now do things like ;
pizzaTruck.driveTo(beach);
pizzaTruck.cook(pizzaWithExtraAnchovies);
Ok, this silly story was to make the point that it is no simulation of multiple inheritance, it is real multiple inheritance with the proviso that you can only inherit the contract, only inherit from empty abstract base classes which are called interfaces.
(update: with the coming of default methods interfaces now can also provide some behavior to be inherited)
You're probably confused because you view multiple inheritance locally, in terms of one class inheriting implementation details from multiple parents. This is not possible in Java (and often leads to abuse in languages where it's possible).
Interfaces allow multiple inheritance of types, e.g. a class Waterfowl extends Bird implements Swimmer can be used by other classes as if it were a Bird and as if it were a Swimmer. This is the the deeper meaning of multiple inheritance: allowing one object to act like it belongs to several unrelated different classes at once.
Here is a way to achieve multiple inheritance through interfaces in java.
What to achieve?
class A extends B, C // this is not possible in java directly but can be achieved indirectly.
class B{
public void getValueB(){}
}
class C{
public void getValueC(){}
}
interface cInterface{
public getValueC();
}
class cChild extends C implemets cInterface{
public getValueC(){
// implementation goes here, call the super class's getValueC();
}
}
// Below code is **like** class A extends B, C
class A extends B implements cInterface{
cInterface child = new cChild();
child.getValueC();
}
given the two interfaces below...
interface I1 {
abstract void test(int i);
}
interface I2 {
abstract void test(String s);
}
We can implement both of these using the code below...
public class MultInterfaces implements I1, I2 {
public void test(int i) {
System.out.println("In MultInterfaces.I1.test");
}
public void test(String s) {
System.out.println("In MultInterfaces.I2.test");
}
public static void main(String[] a) {
MultInterfaces t = new MultInterfaces();
t.test(42);
t.test("Hello");
}
}
We CANNOT extend two objects, but we can implement two interfaces.
Interfaces don't simulate multiple inheritance. Java creators considered multiple inheritance wrong, so there is no such thing in Java.
If you want to combine the functionality of two classes into one - use object composition. I.e.
public class Main {
private Component1 component1 = new Component1();
private Component2 component2 = new Component2();
}
And if you want to expose certain methods, define them and let them delegate the call to the corresponding controller.
Here interfaces may come handy - if Component1 implements interface Interface1 and Component2 implements Interface2, you can define
class Main implements Interface1, Interface2
So that you can use objects interchangeably where the context allows it.
It's pretty simple. You can implement more than one interface in a type. So for example, you could have an implementation of List that is also an instance of Deque (and Java does...LinkedList).
You just can't inherit implementations from multiple parents (i.e. extend multiple classes). Declarations (method signatures) are no problem.
You know what, coming from the perspective of a JavaScript dev trying to understand what the heck is going on with this stuff, I'd like to point out a couple things and somebody please tell me what I'm missing here if I'm way off the mark.
Interfaces are really simple. Stupidly, insanely simple. They're as stupidly, insanely simple as people initially think, which is why there are so many duplicate questions on this exact subject because the one reason to use them has been made unclear by people trying to make more of them than they are and there is widespread misuse in every Java server-side code-base I've ever been exposed to.
So, why would you want to use them? Most of the time you wouldn't. You certainly wouldn't want to use them ALL the time as many seem to think. But before I get to when you would, let's talk about what they're NOT.
Interfaces are NOT:
in any way a workaround for any sort of inheritance mechanism that Java lacks. They have nothing to do with inheritance, they never did, and in no way simulate anything inheritance-like.
necessarily something that helps you with stuff you wrote, so much as it helps the other guy write something meant to be interfaced by your stuff.
They really are as simple as you think they are on first glance. People misuse stupidly all the time so it's hard to understand what the point is. It's just validation/testing. Once you've written something conforms to an interface and works, removing that "implements" code won't break anything.
But if you're using interfaces correctly, you wouldn't want to remove it because having it there gives the next developer a tool for writing an access layer for another set of databases or web services that they want the rest of your app to continue using because they know their class will fail until they get the 100% complete-as-expected-interface in place. All interfaces do is validate your class and establish that you have in fact implemented an interface as you promised you would. Nothing more.
They're also portable. By exposing your interface definitions you can give people wanting to use your unexposed code a set of methods to conform to in order for their objects to use it correctly. They don't have to implement the interfaces. They could just jot them down on a piece of notepad paper and double-check that. But with the interface you have more of a guarantee nothing is going to try to work until it has a proper version of the interface in question.
So, any interface not likely to ever be implemented more than once? Completely useless. Multiple-inheritance? Stop reaching for that rainbow. Java avoids them for a reason in the first place and composited/aggregate objects are more flexible in a lot of ways anyway. That's not to say interfaces can't help you model in ways that multiple-inheritance allows but it's really not inheritance in any way shape or form and shouldn't be seen as such. It's just guaranteeing that your code won't work until you've implemented all of the methods you established that you would.
It's not a simulation of multiple inheritance. In java you can't inherit from two classes, but if you implements two interfaces "it seems like you inherited from two different classes" because you can use your class as any of your two intefaces.
For example
interface MyFirstInteface{
void method1();
}
interface MySecondInteface{
void method2();
}
class MyClass implements MyFirstInteface, MySecondInteface{
public void method1(){
//Method 1
}
public void method2(){
//Method 2
}
public static void main(String... args){
MyFirstInterface mfi = new MyClass();
MySecondInterface msi = new MyClass();
}
}
This will work and you can use mfi and msi, it seems like a multi inheritance, but it's not because you don't inherit anything, you just rewrite public methods provided by the interfaces.
You need to be precise:
Java allows multiple inheritance of interface, but only single inheritance of implementation.
You do multiple inheritance of interface in Java like this:
public interface Foo
{
String getX();
}
public interface Bar
{
String getY();
}
public class MultipleInterfaces implements Foo, Bar
{
private Foo foo;
private Bar bar;
public MultipleInterfaces(Foo foo, Bar bar)
{
this.foo = foo;
this.bar = bar;
}
public String getX() { return this.foo.getX(); }
public String getY() { return this.bar.getY(); }
}
Just by the way, the reason why Java does not implement full multiple inheritance is because it creates ambiguities. Suppose you could say "A extends B, C", and then both B and C have a function "void f(int)". Which implementation does A inherit? With Java's approach, you can implement any number of interfaces, but interfaces only declare a signature. So if two interfaces include functions with the same signature, fine, your class must implement a function with that signature. If interfaces you inherit have functions with different signatures, then the functions have nothing to do with each other, so there is no question of a conflict.
I'm not saying this is the only way. C++ implements true multiple inheritance by establishing precedence rules of which implementation wins. But the authors of Java decided to eliminate the ambiguity. Whether because of a philosophical belief that this made for cleaner code, or because they didn't want to do all the extra work, I don't know.
It's not fair to say that interfaces 'simulate' multiple inheritance.
Sure, your type can implement multiple interfaces and act as many different types polymorphically. However, you obviously won't inherit behaviour or implementations under this arrangement.
Generally look at composition where you think you may need multiple inheritance.
OR A potential solution to achieving something multiple inheritance like is the Mixin interface - http://csis.pace.edu/~bergin/patterns/multipleinheritance.html. Use with care!
They don't.
I think that the confusion comes from people believing that implementing an interface constitutes some form of inheritance. It doesn't; the implementation can simply be blank, no behavior is forced by the act or guaranteed through any contract. A typical example is the Clonable-interface, which while alluding to lots of great functionality, which defines so little that's it's essentially useless and potentially dangerous.
What do you inherit by implementing an interface? Bubkes! So in my opinion, stop using the words interface and inheritance in the same sentence. As Michael Borgwardt said, an interface is not a definition but an aspect.
You can actually "inherit" from multiple concrete classes if they implement interfaces themselves. innerclasses help you achieve that:
interface IBird {
public void layEgg();
}
interface IMammal {
public void giveMilk();
}
class Bird implements IBird{
public void layEgg() {
System.out.println("Laying eggs...");
}
}
class Mammal implements IMammal {
public void giveMilk() {
System.out.println("Giving milk...");
}
}
class Platypus implements IMammal, IBird {
private class LayingEggAnimal extends Bird {}
private class GivingMilkAnimal extends Mammal {}
private LayingEggAnimal layingEggAnimal = new LayingEggAnimal();
private GivingMilkAnimal givingMilkAnimal = new GivingMilkAnimal();
#Override
public void layEgg() {
layingEggAnimal.layEgg();
}
#Override
public void giveMilk() {
givingMilkAnimal.giveMilk();
}
}
I'd like to point out something that bit me in the behind, coming from C++ where you can easily inherit many implementations too.
Having a "wide" interface with many methods means that you'll have to implement a lot of methods in your concrete classes and you can't share these easily across implementations.
For instance:
interface Herbivore {
void munch(Vegetable v);
};
interface Carnivore {
void devour(Prey p);
}
interface AllEater : public Herbivore, Carnivore { };
class Fox implements AllEater {
...
};
class Bear implements AllEater {
...
};
In this example, Fox and Bear cannot share a common base implementation for both it's interface methods munch and devour.
If the base implementations look like this, we'd maybe want to use them for Fox and Bear:
class ForestHerbivore implements Herbivore
void munch(Vegetable v) { ... }
};
class ForestCarnivore implements Carnivore
void devour(Prey p) { ... }
};
But we can't inherit both of these. The base implementations need to be member variables in the class and methods defined can forward to that. I.e:
class Fox implements AllEater {
private ForestHerbivore m_herbivore;
private ForestCarnivore m_carnivore;
void munch(Vegetable v) { m_herbivore.munch(v); }
void devour(Prey p) { m_carnivore.devour(p); }
}
This gets unwieldy if interfaces grow (i.e. more than 5-10 methods...)
A better approach is to define an interface as an aggregation of interfaces:
interface AllEater {
Herbivore asHerbivore();
Carnivore asCarnivore();
}
This means that Fox and Bear only has to implement these two methods, and the interfaces and base classes can grow independetly of the aggregate AllEater interface that concerns the implementing classes.
Less coupling this way, if it works for your app.
I don't think they do.
Inheritance is specifically an implementation-oriented relationship between implementations. Interfaces do not provide any implementation information at all, but instead define a type. To have inheritance, you need to specifically inherit some behaviors or attributes from a parent class.
I believe there is a question here somewhere specifically about the role of interfaces and multiple inheritance, but I can't find it now...
There's really no simulation of multiple inheritance in Java.
People will sometimes say that you can simulate multiple inheritance using Interfaces because you can implement more than one interface per class, and then use composition (rather than inheritance) in your class to achieve the behaviors of the multiple classes that you were trying to inherit from to begin with.
If it makes sense in your object model, you can of course inherit from one class and implement 1 or more interfaces as well.
There are cases where multiple-inheritance turns to be very handy and difficult to replace with interfaces without writing more code. For example, there are Android apps that use classes derived from Activity and others from FragmentActivity in the same app. If you have a particular feature you want to share in a common class, in Java you will have to duplicate code instead of let child classes of Activity and FragmentsActivity derive from the same SharedFeature class. And the poor implementation of generics in Java doesn't help either because writing the following is illegal:
public class SharedFeature<T> extends <T extends Activity>
...
...
There is no support for multiple inheritance in java.
This story of supporting multiple inheritance using interface is what we developers cooked up. Interface gives flexibility than concrete classes and we have option to implement multiple interface using single class. This is by agreement we are adhering to two blueprints to create a class.
This is trying to get closer to multiple inheritance. What we do is implement multiple interface, here we are not extending (inheriting) anything. The implementing class is the one that is going to add the properties and behavior. It is not getting the implementation free from the parent classes. I would simply say, there is no support for multiple inheritance in java.
No, Java does not support multiple inheritance.
Neither using class nor using interface. Refer to this link for more info
https://devsuyed.wordpress.com/2016/07/21/does-java-support-multiple-inheritance
I also have to say that Java doesn't support multiple inheritance.
You have to differentiate the meaning between extends and implements keywords in Java. If we use extends, we are actually inheriting the class after that keyword. But, in order to make everything simple, we can't use extends more than once. But you can implement as many Interfaces as you wish.
If you implement an interface, there's a zero chance that you will miss the implementation of all the methods in each interface (Exception: default implementations of interface methods introduced in Java 8) So, you are now fully aware of what is happening with the things that you have embedded to your fresh class.
Why Java doesn't allow multiple inheritance is actually, multiple inheritance makes the code somewhat complex. Sometimes, two methods of parent classes might conflict due to having the same signatures. But if you are forced to implement all the methods manually, you will get the full understanding about what's going on, as I mentioned above. It makes your code more understandable to you.
If you need more info on Java interfaces, check out this article, http://www.geek-programmer.com/introduction-to-java-interfaces/
Between two Java class multiple Inheritance directly is not possible. In this case java recommend Use to interface and declare method inside interface and implement method with Child class.
interface ParentOne{
public String parentOneFunction();
}
interface ParentTwo{
public String parentTwoFunction();
}
class Child implements ParentOne,ParentTwo{
#Override
public String parentOneFunction() {
return "Parent One Finction";
}
#Override
public String parentTwoFunction() {
return "Parent Two Function";
}
public String childFunction(){
return "Child Function";
}
}
public class MultipleInheritanceClass {
public static void main(String[] args) {
Child ch = new Child();
System.out.println(ch.parentOneFunction());
System.out.println(ch.parentTwoFunction());
System.out.println(ch.childFunction());
}
}

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Java doesn't allow multiple inheritance, but it allows implementing multiple interfaces. Why?
Because interfaces specify only what the class is doing, not how it is doing it.
The problem with multiple inheritance is that two classes may define different ways of doing the same thing, and the subclass can't choose which one to pick.
One of my college instructors explained it to me this way:
Suppose I have one class, which is a Toaster, and another class, which is NuclearBomb. They both might have a "darkness" setting. They both have an on() method. (One has an off(), the other doesn't.) If I want to create a class that's a subclass of both of these...as you can see, this is a problem that could really blow up in my face here.
So one of the main issues is that if you have two parent classes, they might have different implementations of the same feature — or possibly two different features with the same name, as in my instructor's example. Then you have to deal with deciding which one your subclass is going to use. There are ways of handling this, certainly — C++ does so — but the designers of Java felt that this would make things too complicated.
With an interface, though, you're describing something the class is capable of doing, rather than borrowing another class's method of doing something. Multiple interfaces are much less likely to cause tricky conflicts that need to be resolved than are multiple parent classes.
Because inheritance is overused even when you can't say "hey, that method looks useful, I'll extend that class as well".
public class MyGodClass extends AppDomainObject, HttpServlet, MouseAdapter,
AbstractTableModel, AbstractListModel, AbstractList, AbstractMap, ...
The answer of this question is lies in the internal working of java compiler(constructor chaining).
If we see the internal working of java compiler:
public class Bank {
public void printBankBalance(){
System.out.println("10k");
}
}
class SBI extends Bank{
public void printBankBalance(){
System.out.println("20k");
}
}
After compiling this look like:
public class Bank {
public Bank(){
super();
}
public void printBankBalance(){
System.out.println("10k");
}
}
class SBI extends Bank {
SBI(){
super();
}
public void printBankBalance(){
System.out.println("20k");
}
}
when we extends class and create an object of it, one constructor chain will run till Object class.
Above code will run fine. but if we have another class called Car which extends Bank and one hybrid(multiple inheritance) class called SBICar:
class Car extends Bank {
Car() {
super();
}
public void run(){
System.out.println("99Km/h");
}
}
class SBICar extends Bank, Car {
SBICar() {
super(); //NOTE: compile time ambiguity.
}
public void run() {
System.out.println("99Km/h");
}
public void printBankBalance(){
System.out.println("20k");
}
}
In this case(SBICar) will fail to create constructor chain(compile time ambiguity).
For interfaces this is allowed because we cannot create an object of it.
For new concept of default and static method kindly refer default in interface.
Hope this will solve your query.
Thanks.
You can find accurate answer for this query in oracle documentation page about multiple inheritance
Multiple inheritance of state: Ability to inherit fields from multiple classes
One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes
If multiple inheritance is allowed and When you create an object by instantiating that class, that object will inherit fields from all of the class's superclasses. It will cause two issues.
What if methods or constructors from different super classes instantiate the same field?
Which method or constructor will take precedence?
Multiple inheritance of implementation: Ability to inherit method definitions from multiple classes
Problems with this approach: name conflicts and ambiguity. If a subclass and superclass contain same method name (and signature), compiler can't determine which version to invoke.
But java supports this type of multiple inheritance with default methods, which have been introduced since Java 8 release. The Java compiler provides some rules to determine which default method a particular class uses.
Refer to below SE post for more details on resolving diamond problem:
What are the differences between abstract classes and interfaces in Java 8?
Multiple inheritance of type: Ability of a class to implement more than one interface.
Since interface does not contain mutable fields, you do not have to worry about problems that result from multiple inheritance of state here.
Java does not support multiple inheritance because of two reasons:
In java, every class is a child of Object class. When it inherits from more than one super class, sub class gets the ambiguity to
acquire the property of Object class..
In java every class has a constructor, if we write it explicitly or not at all. The first statement is calling super() to invoke the
supper class constructor. If the class has more than one super class, it
gets confused.
So when one class extends from more than one super class, we get compile time error.
Java supports multiple inheritance through interfaces only. A class can implement any number of interfaces but can extend only one class.
Multiple inheritance is not supported because it leads to deadly diamond problem. However, it can be solved but it leads to complex system so multiple inheritance has been dropped by Java founders.
In a white paper titled “Java: an Overview” by James Gosling in February 1995(link - page 2) gives an idea on why multiple inheritance is not supported in Java.
According to Gosling:
"JAVA omits many rarely used, poorly understood, confusing features of
C++ that in our experience bring more grief than benefit. This
primarily consists of operator overloading (although it does have
method overloading), multiple inheritance, and extensive automatic
coercions."
Implementing multiple interfaces is very useful and doesn't cause much problems to language implementers nor programmers. So it is allowed. Multiple inheritance while also useful, can cause serious problems to users (dreaded diamond of death). And most things you do with multiple inheritance can be also done by composition or using inner classes. So multiple inheritance is forbidden as bringing more problems than gains.
It is said that objects state is referred with respect to the fields in it and it would become ambiguous if too many classes were inherited. Here is the link
http://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
Since this topic is not close I'll post this answer, I hope this helps someone to understand why java does not allow multiple inheritance.
Consider the following class:
public class Abc{
public void doSomething(){
}
}
In this case the class Abc does not extends nothing right? Not so fast, this class implicit extends the class Object, base class that allow everything work in java. Everything is an object.
If you try to use the class above you'll see that your IDE allow you to use methods like: equals(Object o), toString(), etc, but you didn't declare those methods, they came from the base class Object
You could try:
public class Abc extends String{
public void doSomething(){
}
}
This is fine, because your class will not implicit extends Object but will extends String because you said it. Consider the following change:
public class Abc{
public void doSomething(){
}
#Override
public String toString(){
return "hello";
}
}
Now your class will always return "hello" if you call toString().
Now imagine the following class:
public class Flyer{
public void makeFly(){
}
}
public class Bird extends Abc, Flyer{
public void doAnotherThing(){
}
}
Again class Flyer implicit extends Object which has the method toString(), any class will have this method since they all extends Object indirectly, so, if you call toString() from Bird, which toString() java would have to use? From Abc or Flyer? This will happen with any class that try to extends two or more classes, to avoid this kind of "method collision" they built the idea of interface, basically you could think them as an abstract class that does not extends Object indirectly. Since they are abstract they will have to be implemented by a class, which is an object (you cannot instanciate an interface alone, they must be implemented by a class), so everything will continue to work fine.
To differ classes from interfaces, the keyword implements was reserved just for interfaces.
You could implement any interface you like in the same class since they does not extends anything by default (but you could create a interface that extends another interface, but again, the "father" interface would not extends Object"), so an interface is just an interface and they will not suffer from "methods signature colissions", if they do the compiler will throw a warning to you and you will just have to change the method signature to fix it (signature = method name + params + return type).
public interface Flyer{
public void makeFly(); // <- method without implementation
}
public class Bird extends Abc implements Flyer{
public void doAnotherThing(){
}
#Override
public void makeFly(){ // <- implementation of Flyer interface
}
// Flyer does not have toString() method or any method from class Object,
// no method signature collision will happen here
}
For the same reason C# doesn't allow multiple inheritence but allows you to implement multiple interfaces.
The lesson learned from C++ w/ multiple inheritence was that it lead to more issues than it was worth.
An interface is a contract of things your class has to implement. You don't gain any functionality from the interface. Inheritence allows you to inherit the functionality of a parent class (and in multiple-inheritence, that can get extremely confusing).
Allowing multiple interfaces allows you to use Design Patterns (like Adapter) to solve the same types of issues you can solve using multiple inheritence, but in a much more reliable and predictable manner.
For example two class A,B having same method m1(). And class C extends both A, B.
class C extends A, B // for explaining purpose.
Now, class C will search the definition of m1. First, it will search in class if it didn't find then it will check to parents class. Both A, B having the definition So here ambiguity occur which definition should choose.
So JAVA DOESN'T SUPPORT MULTIPLE INHERITANCE.
in simple manner we all know, we can inherit(extends) one class but we can implements so many interfaces.. that is because in interfaces we don't give an implementation just say the functionality. suppose if java can extends so many classes and those have same methods.. in this point if we try to invoke super class method in the sub class what method suppose to run??, compiler get confused
example:- try to multiple extends
but in interfaces those methods don't have bodies we should implement those in sub class..
try to multiple implements
so no worries..
Multiple inheritance is not supported by class because of ambiguity.
(this point is explained clearly in above answers using super keyword)
Now for interfaces,
upto Java 7, interfaces could not define the implementation of methods. So if class implements from multiple interfaces having same method signature then implementation of that method is to be provided by that class.
from java 8 onwards, interfaces can also have implementation of methods. So if class implements two or more interfaces having same method signature with implementation, then it is mandated to implement the method in that class also.
From Java 9 onwards, interfaces can contain Static methods, Private methods, Private Static methods.
Modifications in features of Interfaces (over java version-7,8,9)
Because an interface is just a contract. And a class is actually a container for data.
Consider a scenario where Test1, Test2 and Test3 are three classes. The Test3 class inherits Test2 and Test1 classes. If Test1 and Test2 classes have same method and you call it from child class object, there will be ambiguity to call method of Test1 or Test2 class but there is no such ambiguity for interface as in interface no implementation is there.
Java does not support multiple inheritance , multipath and hybrid inheritance because of the following ambiguity
problem.
Scenario for multiple inheritance: Let us take class A , class B , class C. class A has alphabet(); method , class B has also alphabet(); method. Now class C extends A, B and we are creating object to the subclass i.e., class C , so C ob = new C(); Then if you want call those methods ob.alphabet(); which class method takes ? is class A method or class B method ? So in the JVM level ambiguity problem occurred. Thus Java does not support multiple inheritance.
multiple inheritance
Reference Link: https://plus.google.com/u/0/communities/102217496457095083679
Take for example the case where Class A has a getSomething method and class B has a getSomething method and class C extends A and B. What would happen if someone called C.getSomething? There is no way to determine which method to call.
Interfaces basically just specify what methods a implementing class needs to contain. A class that implements multiple interfaces just means that class has to implement the methods from all those interfaces. Whci would not lead to any issues as described above.
the image explaining the problem with multiple inheritances.
What is the inherited member of the derived class? it is still private or publically available in the derived class?
For not getting this type of problem in Java they removed multiple inheritance. This image is a simple example of an object-oriented programming problem.
* This is a simple answer since I'm a beginner in Java *
Consider there are three classes X,Y and Z.
So we are inheriting like X extends Y, Z
And both Y and Z is having a method alphabet() with same return type and arguments. This method alphabet() in Y says to display first alphabet and method alphabet in Z says display last alphabet.
So here comes ambiguity when alphabet() is called by X. Whether it says to display first or last alphabet???
So java is not supporting multiple inheritance.
In case of Interfaces, consider Y and Z as interfaces. So both will contain the declaration of method alphabet() but not the definition. It won't tell whether to display first alphabet or last alphabet or anything but just will declare a method alphabet(). So there is no reason to raise the ambiguity. We can define the method with anything we want inside class X.
So in a word, in Interfaces definition is done after implementation so no confusion.
It is a decision to keep the complexity low.
With hybrid inheritance, things would have been more complicated to implement, and anyways what is achievable by multiple inheritances is also with other ways.

Categories