As Java 9 is going to allow us to define private and private static methods too in interfaces, what would be the remaining difference in interface and class?
Moreover, is Java moving towards multiple inheritance slowly?
Private interface methods in Java 9 behave exactly like other private methods: They must have a body (even in abstract classes) and can neither be called nor overridden by subclasses. As such they do not really interact with inheritance. Talking of which (and particularly multiple inheritance), there are (at least?) three kinds of it:
Inheritance of types means that one type can be another type, e.g. String is an Object. Java allowed multiple inheritance of types from day one (via interfaces).
Inheritance of behavior means that one type can inherit the behavior of another type. Before Java 8, only classes could implement methods, so there was only single inheritance of this kind. With Java 8 came default methods, which allowed interfaces to implement methods, thus giving Java multiple inheritance of behavior.
Inheritance of state means that a type inherits another type's internal state (i.e. fields). As it stands (Java 9 and everything currently proposed for future Java versions), only classes can have state, so there is only single inheritance of this kind.
As you can see private interface methods do not add anything here.
Regarding your question of how interfaces and classes compare, there are two main differences: multiple inheritance and state. Interfaces support the former, classes can have the latter. Since state is kind-of important in typical OOP, classes will remain relevant. 😉
If there were a way for an interface to force an implementation to have a particular non-public field or straight-out define one itself, the game would change and interfaces could compete with classes.
Private methods are not inherited by subclasses, so this feature doesn't affect implementation classes. I believe the private methods in interfaces allow us to share code between default methods.
Java interfaces still cannot have non-static members. That's a big difference and not multiple inheritance IMO.
Java 9 interfaces still cannot contain fields and constructors. This makes a huge difference between classes and interfaces, so Java 9 is far from multiple inheritance.
Java Interface in version 9 have private methods but static private. The feature has been introduced to allow modular methods. One function should work with one responsibility instead of using lengthy default methods. It has nothing to do with multiple Inheritance. The more private static methods, the more you will be able to write the clean and reusable code. Anyways, static methods whether public or protected can not be overridden.
Although its an old question let me give my input on it as well :)
abstract class: Inside abstract class we can declare instance
variables, which are required to the child class
Interface: Inside interface every variables is always public static
and final we cannot declare instance variables
abstract class: Abstract class can talk about state of object
Interface: Interface can never talk about state of object
abstract class: Inside Abstract class we can declare constructors
Interface: Inside interface we cannot declare constructors as purpose of
constructors is to initialize instance variables. So what
is the need of constructor there if we cannot have instance
variables in interfaces.
abstract class: Inside abstract class we can declare instance and static blocks
Interface: Interfaces cannot have instance and static blocks.
abstract class: Abstract class cannot refer lambda expression
Interfaces: Interfaces with single abstract method can refer lambda expression
abstract class: Inside abstract class we can override OBJECT CLASS methods
Interfaces: We cannot override OBJECT CLASS methods inside interfaces.
I will end on the note that:
Default method concepts/static method concepts in interface came just to save implementation classes but not to provide meaningful useful implementation. Default methods/static methods are kind of dummy implementation, "if you want you can use them or you can override them (in case of default methods) in implementation class" Thus saving us from implementing new methods in implementation classes whenever new methods in interfaces are added. Therefore interfaces can never be equal to abstract classes.
Related
How to make a class only extendable not directly usable and with a different implementation for the method by every sub class? I thought about interfaces but interfaces doesn't obligate me to initialize variables just obligates me to implement the methods I want something that obligates every single sub class to initialize a some specific variables they extend.
Add the abstract modifier. That is
public abstract class MyClass { ... }
As he said what you want is an Abstract Class, an abstract class is like a template:
Thi is what Oracle say:
Abstract Classes Compared to Interfaces
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.
Which should you use, abstract classes or interfaces?
Consider using abstract classes if any of these statements apply to your situation:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your situation:
You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.
Here is more information
https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
and you can use as he said
abstract class Name{}
Java 8 introduced default and static methods on interfaces. So now you can have concrete implementations in your interface whether using default or static methods.
The reason Java claimed to add these two new kind of methods is "ensure binary compatibility with code written for older versions of those interfaces".
My question:
Why to distort the interface original concept that suppose to be
fully abstract in order to support existing architectural problems?
What is the difference between using an abstract class and the new version of the interface other than the ability of a class to extend multiple interfaces?
The reason java claimed to add these 2 new kind of methods is "ensure binary compatibility with code written for older versions of those interfaces".
This applies only to default methods (not static methods) and omits some context. From Goetz, State of the Lambda:
The purpose of default methods ... is to enable interfaces to be evolved in a compatible manner after their initial publication.
The main goal is to allow interface evolution, that is, the addition of new methods. If a new method is added to an interface, existing classes that implement the interface would be missing an implementation, which would be incompatible. To be compatible, an implementation has to come from somewhere, so it is provided by default methods.
Why to distort the interface original concept that suppose to be fully abstract in order to support existing architectural problems?
The main intent of a Java interface is to specify a contract that any class can implement without having to alter its position in the class hierarchy. It's true that, prior to Java 8, interfaces were purely abstract. However, this is not an essential property of interfaces. Even when default methods are included, an interface at its heart still specifies a contract upon the implementing class. The implementing class can override default methods, so the class is still in complete control of its implementation. (Note also that default methods cannot be final.)
What is the difference between using an abstract class and the new version of the interface other than the ability of a class to extend multiple interfaces?
The ability of a class to extend multiple interfaces is closely related to another difference between interfaces and abstract classes, namely that interfaces cannot contain state. This is the primary difficulty with allowing multiple inheritance: if a superclass were to appear multiple times in the ancestry of a class, would that superclass' state appear just once or several times? (This is the so-called "diamond problem.")
Another difference is that abstract classes can define methods and fields to be shared with subclasses, but not with callers, by using protected and package-private access levels. Interfaces can have only public methods.
(In Java 9, support for private methods has been added. This is useful for implementation sharing among default or static methods of an interface.)
Finally, static methods in interfaces don't affect class inheritance, nor are they part of the interface's contract. They are merely a way of organizing utility methods in more convenient fashion. For example, a common use of static methods in an interface is for static factory methods. If static methods weren't allowed in interfaces, static factory methods would have to be put on a companion class. Allowing static methods in interfaces lets such methods be grouped with the interface itself, when doing so is appropriate.
The problem is, that you can never extend an Interface with a new method without breaking compatibility. Existing classes would not implement the method and therefore not run with the new version of code which use this method.
This was a major problem for the Java Class Library itself as it cannot add often asked for methods in basic interfaces (like Collections). This was the main driver for implementing default methods for interfaces.
The difference between this new method and using an abstract class (which is a quite good pattern for this problem in some cases) is, that you cannot inherit from multiple abstract classes. But you can easily implement multiple interfaces.
The static methods in interfaces are less clear, I think they are here to help you implement the default methods (if two default methods have same code, they both can call to a static method).
I'm new to Java programming and right now, I am trying to understand OOP concepts (inheritance, polymorphisms, etc.).
I know that, when a subclass extends a superclass (abstract or not), subclass constructor calls the constructor of that superclass first (super()).
My questions are:
1) Is it the same case for Interfaces? I've read some articles saying that interfaces don't have constructors, so how exactly are they being extended?
2) How come multiple inheritance is not supported in Java but an interface can "extend" multiple other interfaces?
Thanks in advance.
1) Is it the same case for Interfaces? I've read some articles saying that interfaces don't have constructors, so how exactly are they being extended?
Yes, there is no constructor in an interface, you will have to define a concrete class(that implements that interface) to create an object of that interface type.
Example: you can check the profile of java.io.Serializable using javap java.io.Serializable which is:
public interface java.io.Serializable {
}
which says there is no constructor.
2) How come multiple inheritance is not supported in Java but an interface can "extend" multiple other interfaces?
Yes you can extend multiple interfaces, this is because, if two interface contains abstract method with same signature, this will not be an ambiguity to the compiler. But this is not with the case with class, if you will try to extend two classes that have method with same signature then it will be an ambiguity to the compiler for which method to call as method declaration might be different in different class.
Yes, you can do it. An interface can extends multiple interfaces.
interface Maininterface extends inter1, inter2, inter3{
// methods
}
Not only interfaces,A single class can also implements multiple interface. Then obviously a doubt raises, what if two methods have an same method name.
There is a tricky point:
interface A
{
void test();
}
interface B
{
void test();
}
class C implements A, B
{
#Override
public void test() {
}
}
Then single implementation works for both :)
1) Is it the same case for Interfaces?
Not really. Constructors for an interface don't really make sense, as constructors define some initial state, but interfaces don't have state. So constructors aren't being called.
I've read some articles saying that interfaces don't have constructors, so how exactly are they being extended?
You should think of extending an interface as more extending a type -- that is, expanding the defined behaviors of something. It's like taking a contract and adding some clauses onto the end -- you're saying "In addition to the methods defined in the superinterface, I want classes implementing this interface to also implement______"
Extending a class is somewhat similar, as you also extend a type, but the thing is that extending a class should be considered to be adding additional state/implementation to a type. Because of this, superclass constructors should be called to make sure that all the state associated with the superclass definitions is properly initialized.
2) How come multiple inheritance is not supported in Java but an interface can "extend" multiple other interfaces?
You have to be careful here, as there isn't just one kind of multiple inheritance. Java does support multiple inheritance of types, which is why you can implement multiple interfaces, which define types. What Java doesn't support is multiple inheritance of state (and multiple inheritance of implementation wasn't allowed until Java 8. See note below). This is why you can only extend 1 class -- because classes define state.
Thus, because you're allowed to inherit multiple types, extending multiple interfaces is perfectly OK for a given interface. It's like taking one contract and stapling several other contracts to the back of it. As long as the implementing class follows the entire thing, your program should compile.
Note: As of Java 8, you can now inherit multiple implementations, through default methods in interfaces. In the case of a conflict, the programmer must explicitly implement the method in question.
First of all try to clear the concept of inheritance . The basic concept behind Inheritance is to inheriting (getting ) all the property(variables and methods)(considering access modifier ) of parent class with our rewriting them in the child class.
Suppose we have a Class A,
class A{
public void doA()
{
}
}
now if class B extends A(mark the literal meaning of extends) it will get the method doA(), inherently. If you look at the literal part actually B extends A it seems B is an extended version of A.
Now Come to the Interface part. If I have a interface InA
interface InA{
doInA();
}
and i try to inherit it in class B i need to implement (mark the literal again) it. So i will get the method doInA() it B but i need to give it a body.
In case of of Interface to Interface, Now as you have used two key word for inheritance. If i ask you that an interface InB will inherit interface InA what key work will you chose among extends and implements? doesn't the extends sounds more logical. Because InB implementing nothing its just getting bigger and it will be an extended version of InA.
Now Lets answer you two key question:
1.Is it the same case for Interfaces?
Yes and No. actually the constructor of parent only be called when the constructor of child is called. So as you never can call the constructor of child Interface the constructor of parent interface will never be called. Its doesn't call the parent constructor but still it reserve the technique of constructor calling .
2) How come multiple inheritance is not supported in Java but an interface can "extend" multiple other interfaces?
Have a look at this Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?
What is the difference between an abstract class and an interface?
Interfaces are stateless. They cannot gave variables, though they can have constants.
Also, interfaces provide the 'design by contract ' capability.
Abstract classes force a concrete implementation, where interfaces allow more flexibility because any class that implements that interface can be substituted at run time.
Also, since interfaces simply describe behavior that is exposed, not the implementation, then thet allow for multiple inheritance.
Also abstract classes are more a design convenience as they provide for compiler enforcement in that subclasses must implement abstract methods.
Interfaces and abstract classes are related, but serve different purposes.
At runtime the type of object is checked and the corresponding class method invoked.
This is also called late binding.
This is done by the runtime VM not by the programmer thus taking that If Else test out of your program code. So, your code is more flexible and does not depend on the class type to resolve the correct method to call. Thus us also called polymorphism.
An abstract class can have methods implemented. An interface cannot. Also a class can only extend one abstract class, but can implement many interfaces.
Use of interface : There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.
One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java (other than java.lang.Object, the root class of the Java type system) must have exactly one base class; multiple inheritance of classes is not allowed. Furthermore, a Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.
Another use of interfaces is being able to use an object without knowing its type of class, but rather only that it implements a certain interface.
Difference bw abstract class and interface : Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also. A Java Interface can contain only method declarations and public static final constants and doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present. An abstract class means the class must be extended. An abstract class must be extended by first concrete class in the inheritance tree. In the abstract class we can have both declaration and definition of a method but in interfaces there are only method signatures, no definition at all. An interface is like a 100% pure abstract class. A class can extend only one class but can implement multiple interfaces. Interfaces provides multiple inheritance without causing deadly diamond of death problem.
Extensive discussions here :
Abstract classes and interfaces in C#
Do/can abstract classes replace interfaces?
Disadvantage : when you have an 1000 class implementing an interface in your library, tomorrow if you want to have an additional method in interface , then changes should be reflected everywhere
This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 5 years ago.
In Java, you can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. That being the case, can you use abstract classes instead of interfaces?
Not always:
a class can extend only one class
a class can implement more than one interface
Sun docs make a more detailed comparison:
Abstract Classes versus Interfaces
Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.
By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).
In some cases you can use an abstract class instead of interface. However, it is hardly ever a good idea to do so. In general you should use the rule:
Interfaces specify behaviour.
Abstract classes specify implementation.
The other "problem" with using abstract classes is that you can then no longer implement mixins, that is you can implement multiple interfaces, however you can only extend one abstract class.
One point missing from the answers here is the idea of who will be implementing the interface.
If your component wants to return instances of abstract types to its callers, where the concrete types are defined internally and hidden from callers, use an interface. Conversely, if your component consumes or accepts instances of abstract types that its callers must implement, abstract classes are usually a better choice.
Anticipating evolution and maintaining binary compatibility tips the scales here. With an abstract class, you can add methods and, if you provide a base implementation, existing implementations of the abstract class will continue to work fine. With an interface, adding a method breaks binary compatibility, for no existing implementation could possibly continue to compile properly without changing to define the new method.
The Apache Cactus project has a good discussion on how to resolve these obligations.
To answer your question, yes you could use an abstract class (providing no implementation) instead of an interface but I'd consider this bad practice:
You've used up your "one-shot" at inheritance (without gaining any benefit).
You cannot inherit from multiple abstract classes but you can implement multiple interfaces.
I would advocate the use of abstract classes more in situations where you wish to provide a partial implementation of a class, possibly delegating some behavior to concrete subclass implementations.
A class in java can inherit from multiple interfaces, but only from one abstract class.
An interface cannot define any code, in an abstract class, you can define code (i.e. default behaviour of methods)
Abstract classes and interfaces are complementary.
For instance when creating an API you will want to present interfaces to the client, so that you may always completely change the implementation whereas he does not have to change its code and the user does not rely on implementation when building using your API but just on methods contracts.
Then you will have abstract classes partly implementing these interfaces, in order to
share some common code, which might be used in all (or almost all) implementations for interface, which is obvious
provide default behaviour which could be overridden in 'real' implementations, for instance a toString() method using interfaces methods to create a textual representation of the implementation
preserve implementations compatibility after interface changes, for instance when you add a new method in your interface, you also add a default implementation in the abstract class so that implementations (for instance those made by the user) extending the abstract class still work without changes
Interfaces are much cleaner and light weight. Abstract classes make you dependent on it heavily as you cannot extend any other classes.
Have a look at the interesting article "Why extends is evil" to get an idea about the differences between interface implementation and class inheritance (beside the obvious multi- single restrictions)
Abstract classes are the partial implementation of Abstraction while Interfaces are the fully implementation of Abstraction.Means in Abstract classes we can put methods declaration as well as method body.
We can't create an object of Abstract classes(association) and reuse the class by inheritence(not by association).
By default in interfaces all declared variables are static final and All methods are public.
For Example: In JDK there are only few abstract classes and HttpServlet is one of them which is used in Servlet.So we can't create object of HttpServlet and it can be used only by inheritence.
Main use of interface is when you create the reference of interface and call the method of particular class that's resolved at runtime. So it's always better idea to create reference of interface to call the method.
Interfaces can only hold abstract method, also interfaces can implement multiple interfaces to any class. But an abstract hold abstract and non abstract methods, and abstract methods cannot extend to more then one class.