This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Abstract class vs Interface in Java
(15 answers)
Closed 2 years ago.
Please tell me situation where interface is better than abstract class in Java
I think you have misunderstood the real meaning of interface and abstract class.
Interface is programming structure where you define your functions/services that you want to expose to public or other modules. Kind of a contract where you promise that you are providing some functionalities or services, but hiding the implementation so that implementation can be changed without affecting your contract.
Abstract class is a partially implemented class and it has no real meaning other than serving as a parent for multiple child classes those with real meaning. Abstract class is special parent class that provides default functionalities to multiple child classes. it is created as abstract because of unavailability of suitable concrete parent class.
In a good design, you should always create an interface. But abstract class is optional. If you can not find a concrete parent class, create an abstract class and implement the interface then provide default implementations for those interface functions (if possible) otherwise mark them as abstract functions and leave the implementation to the child classes.
A class can implement multiple interfaces, but it can only extend one abstract class.
Interfaces allow the creation of proxies that encapsulate a concrete class. This is used extensively by frameworks in order to intercept method calls to the concrete class (e.g., for starting a transaction before the method is executed or to write to the log).
Use an interface when you don't need to provide any default implementations.
Here is a nice link comparing the two: Interface vs. Abstract Class
You can only have one direct abstract superclass. Therefore, interfaces are useful if you need to expose two or more interfaces.
Java doesn't have multiple inheritance; thus, you cannot have a class that implements two abstract classes at once. For instance, if you want a MouseListener and an ActionListener in a same class, you have to do it the interface way.
An interface is better than a abstract class when you want multiple classes to implement that interface and when you don't have to inherit default behavior.
In order to provide WebServices or do JMock tests you dont need the actual implementation, you just need an interface definition. Think about it, there is no need to return the implementation to a third party when all they need to do is call your API.
When you need to implements in any class because interface can be implements in any class or interface but abstract class cant do that e.g. in Applet always Applet class extend in our Applet Application in this case we cant extend the abstract class.
Abstract Class : Define or Declare a method which is more important. Example:
Vehicle must have shape and engine. So we put this behaviour is in Abstract class.
abstract class Vehicle {
abstract void shape();
abstract void engine();
}
Interface Class : Other than that properties like move, honk, etc. So interfaces that provide additional behaviour to your concrete class.
interface Honk{
void honk();
}
interface moveable{
void move();
}
class Car extends Vehicle implements Moveable {
#Override
void shape() {
System.out.println("car's shape");
}
#Override
void Engine() {
System.out.println("car's engine");
}
#Override
void move() {
System.out.println("car's can move");
}
}
But I didn't implements Honk behaviour. If you want you can implements multiple interfaces.
Related
I know that an interface cannot implement in another interface as
implementing means writing the body of the methods. This cannot be
done in interfaces as none of the methods in the interface will have
the body. {Upto Java 7}
But I am confused, if this is the reason why interfaces cannot implement one another then why do the interfaces can be implemented in abstract classes. Since abstract classes cannot define all the methods of the interface necessarily. So in a way an abstract class is not implementing all of the methods of the interfaces.
Interfaces cannot use implements because their purpose is to define interfaces, not provide implementation. (They can extend other interfaces, though.) The purpose of classes is to provide implementation, even if only partial.
But like almost all rules, the edges are blurry:
An abstract class doesn't actually have to implement anything.
Now that Java interfaces have default methods, in some sense they can implement an interface, just not using the keyword implements:
interface A {
void foo();
}
interface B extends A {
void bar();
default void foo() {
System.out.println("foo");
}
}
public class Example implements B
{
public static void main(String[] args) throws Exception {
new Example().foo();
}
public void bar() {
}
}
Often, people don't bother to define an interface as distinct from the class, instead using the class both to define the interface to it and provide the implementation of it. (Some purists have an issue with that, but it's very common practice.)
Fundamentally, though: Interfaces are for defining the interface, and classes are for providing the implementation.
First: "This cannot be done in interfaces as none of the methods in the interface will have the body.": It's important to note that this is a little out of date. Interfaces can have method implementations/bodies (default and/or static methods). This is possible since Java 8.
why interfaces can be implemented in abstract classes but not in other interfaces?
Your question may be strictly about the implements keyword declaration as that's the only aspect in which it makes a difference. In this sense, it's a question of design. Abstract classes are classes, interfaces are interfaces. There are differences between these two types of component, the most notable of which, in this case, is that concrete classes cannot inherit from multiple abstract classes.
There are very good answers on SO about the differences between abstract classes and interfaces (such as this).
Conceptually, though, an interface can extends another interface and then provide an implementation for each of the inherited abstract methods with default methods. One could argue that this is an implementation of the super-interface. But when it comes to the specifics of the language, only a class (abstract or not) can declare to implement an interface.
In the end, though, whether concrete methods are in an interface or in an abstract class, before they're used, an object of a concrete class will have to be created (I'm excluding functional interfaces here), so the difference doesn't matter that much.
Interfaces can extend other interfaces.
As for abstract classes: they require the implementation of the interfaces methods as soon as they implement it. However the implementation doesn't have to be in the abstract class but only in the classes that extend the abstract class and are not abstract themselves.
You have to know something. Interfaces Implements Classes and Abstract Class is a Class. From Java Docs
Interface can only be implemented by classes or extended by other
interfaces.
So Why Interface can not Implement another Interface?
Because at time you are Implementing to a Class you are defining how you class behave. So Implementing an Interface to another interface will break the purposes of an Interface. Implements define that you need an implementation of the methods and the Interface doesn't have implementation only Classes.
abstract class CAR
fuelUp () { // implemented }
/ \
interface SPORTER interface TRUCK
driveFast (); moveLoad ();
Is there a way in Java I can get
a class ESTATE that has
the implementation fuelUp of CAR
and also must implement driveFast AND moveLoad?
Extending from multiple classes is not possible and making CAR an interface does not give me an implementation in CAR.
Your Java class can only extend 1 parent class, but it can implement multiple interfaces
Your class definition would be as follows:
class ESTATE extends CAR implements SPORTER, TRUCK {}
For more help, see:
https://stackoverflow.com/a/21263662/4889267
As already identified, you can extend one class and implement multiple interfaces. And in Java 8+, those interfaces can have default implementations.
But to add to this, you can also have various implementations of SPORTER, for instance. You could make use of the SporterAlpha implementation through composition.
class Foo extends Car implements Sporter {
private SporterAlpha sporterAlpha;
public int sporterMethodA(int arg1) { return sporterAlpha.sporterMethodA(arg1); }
}
Repeat as necessary to expose all the SporterAlpha methods necessary.
Thus, you can:
Inherit from no more than one superclass
Implement as many interfaces as necessary
Use default implementations on your interfaces with Java 8+
Use composition as appropriate
I'm 13 and quite new to java. What I can't seem to figure out is how NOT to implement overriding methods in a class from an interface because they are references. I don't want to make a new copy, and I can't just make (insert Class here) extend (the class the interface gets some of its methods from). So I implement it and what do i get?
err: The type Threadmanager must implement the inherited abstract method (the method)
and then it has a list, one of which says "implement uninherited methods".
But I dont want to implement any methods! I want to use them!
Threadmanager tm;
AwtUtils manager = tm;
manager.drawImage(/*params*/)
The above is what i want, the following is what i don't want:
#override
public void drawImage(/*params*/){
...
}
I don't want to redefine the methods in the interface, simply just use them. and I cant have class ThreadManager extends Debugger(.java) because it already extends something. I thought interfaces were a way you could use those methods in another class without inheriting them through "class foo extends bar"
By the way, all the methods referenced in the interface are references to methods in my class Debugger.java which doubles up as a debugger and the game library.
You cannot use methods from an interface. An interface has no code, only definitions. Think of it as a functionality contract that classes implementing it have to fulfill.
For example
public interface Example {
public void method1ToImplement();
public int method2ToImplement(final String input);
}
This is a contract that all classes implementing this interface must fulfill. This means any instantiable class that implements Example has to implement public void method1ToImplement() and public int method2ToImplement(String). This is because you're stating this class fulfills this functionality, so you must implement this funcionality because as of now there's no code for this functionality in your class since the interface contains no code. For example, you cannot use the methods in List, in fact you cannot even create a new List because it's an interface. But you can create and ArrayList and use its methods because it's a non-abstract class implementing the List interface.
Maybe you're confused because you saw somewhere else you can use already implemented methods, for example toString() (which is already implemented in all classes). This is because this method is not defined in an interface but by a parent class (in case of toString() it's Object that implements it).
TL;DR: A class implementing an interface must implement its methods unless it's abstract.
If I'm understanding you right, you want a class to implement an interface, but don't implement its methods. If that's so, you cannot. Implementation of interface methods is mandatory, unless you're writing an abstract class.
I'm guessing there's something missing on your question, so please, provide some code of your Interface and Class so that we could give you a better answer.
I think you're confused about what an interface does. An interface simply defines a contract such that any object which implements the interface must define the methods in the interface. If you have an abstract class, then you must implement the abstract methods of said class for any class that extends the abstract class. The only exception to this is when you extend from a class that has already implemented the abstract methods or interface and you don't want/need to redefine them for subclasses.
You say that you don't want to implement the methods, you just want to use them, but you can't use methods that don't exist. Implementing an interface does not magically define the logic in the methods in the interface--that is your job. Again, it simply states that any objects that implement the interface will have the interfaces' methods defined.
One of the nice things about interfaces is the following: Let's assume that we have a collection of objects that all implement a particular interface, then we can call any method from the interface on all those objects. NB: we can group said objects together by having an array, ArrayList, or what have you that take the interface as the type parameter, ie ArrayList<MyInterface>
More specific example:
Let's consider a Shape interface that solely includes the header for an area method. We can have a bunch of difference types of shapes that implement the Shape interface (circles, squares, etc). In each shape class, we define a method to get the area for said shape. Now, if we have an ArrayList<Shape> shapes =... we can put different types of shapes into that list and do the following:
for (Shape s : shapes)
{
System.out.println(s.area());
}
This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 9 years ago.
Hi I have faced in my SCJP examination this question. If both interface and abstract class having same methods then which one is better to override all methods into my class in java? Please explain me in different scenarios for which one is better to take.
This is interface :
interface ArithmeticMethods {
public abstract void add();
public abstract void sub();
public abstract void div();
public abstract void mul();
}
This is abstract class :
abstract ArithMethods {
public abstract void add();
public abstract void sub();
public abstract void div();
public abstract void mul();
}
This is my class name: ArithMethodImplemenation class.
Now at what scenario I should do like this
public ArithMethodImplemenation implements ArithmeticMethods{
//override all methods of ArithmeticMethods
}
or at what scenario I should do like this
public ArithMethodImplemenation extends ArithMethods{
//override all methods of ArithMethods
}
Please explain me with different scenarios. And my friends also faced this question in so many interviews. But they couldn't succeed.
There is no point in having an empty abstract class with only abstract methods.
Just use an interface instead.
Remember in Java you can extend only one class but can implement multiple interfaces.
I do not see the point of an abstract class with only abstract methods and no fields.
An abstract class is supposed to help you by implementing parts of common functionality to avoid having to rewrite that common code in implementing classes.
In that case the interface is more appropriate as it only defines the method signatures.
You should implement because inheritance primarily meant to inherit all methods from the superclass. Implementation provides a framework where you aren't overriding all your empty inherited methods.
According to the Java Programming Language, Second Edition, by Ken Arnold and James Gosling:
Inheritance - create a new class as an extension of another class, primarily for the purpose
of code reuse. That is, the derived class inherits the public methods and public data of the
base class. Java only allows a class to have one immediate base class, i.e., single class
inheritance.
Interface Inheritance - create a new class to implement the methods defined as part of an
interface for the purpose of subtyping. That is a class that implements an interface “conforms
to” (or is constrained by the type of) the interface. Java supports multiple interface inheritance.
What I mean is:
interface B {...}
interface A extends B {...} // allowed
interface A implements B {...} // not allowed
I googled it and I found this:
implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible.
However, interface is an 100% abstract class, and an abstract class can implement interfaces (100% abstract class) without implement its methods. What is the problem when it is defining as "interface" ?
In details,
interface A {
void methodA();
}
abstract class B implements A {} // we may not implement methodA() but allowed
class C extends B {
void methodA(){}
}
interface B implements A {} // not allowed.
//however, interface B = %100 abstract class B
implements means implementation, when interface is meant to declare just to provide interface not for implementation.
A 100% abstract class is functionally equivalent to an interface but it can also have implementation if you wish (in this case it won't remain 100% abstract), so from the JVM's perspective they are different things.
Also the member variable in a 100% abstract class can have any access qualifier, where in an interface they are implicitly public static final.
implements means a behaviour will be defined for abstract methods (except for abstract classes obviously), you define the implementation.
extends means that a behaviour is inherited.
With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends another interface instead of implementing it.
On a side note, remember that even if an abstract class can define abstract methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.
Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.
However, interface is 100% abstract class and abstract class can
implements interface(100% abstract class) without implement its
methods. What is the problem when it is defining as "interface" ?
This is simply a matter of convention. The writers of the java language decided that "extends" is the best way to describe this relationship, so that's what we all use.
In general, even though an interface is "a 100% abstract class," we don't think about them that way. We usually think about interfaces as a promise to implement certain key methods rather than a class to derive from. And so we tend to use different language for interfaces than for classes.
As others state, there are good reasons for choosing "extends" over "implements."
Hope this will help you a little what I have learned in oops (core java) during my college.
Implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible. An interface can however extend another interface, which means it can add more methods and inherit its type.
Here is an example below, this is my understanding and what I have learnt in oops.
interface ParentInterface{
void myMethod();
}
interface SubInterface extends ParentInterface{
void anotherMethod();
}
and keep one thing in a mind one interface can only extend another interface and if you want to define it's function on some class then only a interface in implemented eg below
public interface Dog
{
public boolean Barks();
public boolean isGoldenRetriever();
}
Now, if a class were to implement this interface, this is what it would look like:
public class SomeClass implements Dog
{
public boolean Barks{
// method definition here
}
public boolean isGoldenRetriever{
// method definition here
}
}
and if a abstract class has some abstract function define and declare and you want to define those function or you can say implement those function then you suppose to extends that class because abstract class can only be extended. here is example below.
public abstract class MyAbstractClass {
public abstract void abstractMethod();
}
Here is an example subclass of MyAbstractClass:
public class MySubClass extends MyAbstractClass {
public void abstractMethod() {
System.out.println("My method implementation");
}
}
Interface is like an abstraction that is not providing any functionality. Hence It does not 'implement' but extend the other abstractions or interfaces.
Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.