Java performance of abstract vs. interface [closed]

-2

In terms of performance, as far as execution speed is concerned, which is faster, execute a method using an abstract class or interface.

    
asked by nullptr 15.10.2016 в 22:23
source

3 answers

6

Abstract or Interface is not related to performance, but to abstraction or structure.

    
answered by 16.10.2016 в 23:05
3

I do not know if I understand the question well but that I know you can not execute any method of an interface but from the class that implements it, so the performance would be the same because in both you would be executing the method of a class.

    
answered by 16.10.2016 в 00:32
1

Generally a Java method executes the code it contains, nothing more, nothing less. That does not depend on the polymorphism. For example:

public  class A() {
    public void metodoUno(){
        // implementacion
    }

    public void metodoDos(){
        // implementacion
    }
}

public interface I() {
    public void metodoTres();
}

public class B extends A implements I{
    @Override
    public metodoTres(){
        // implementacion
    }
}

It is equivalent in performance aspects to

public abstract class A() {
    public void metodoUno(){
        // implementacion
    }

    public void metodoDos(){
        // implementacion
    }

    public abstract void metodoTres();

}

public class B extends A
    @Override
    public metodoTres(){
        // implementacion
    }
}

while the code of the implementation is equivalent.

  • There is no difference between an abstract method implemented in a subclass and an implemented method based on an interface
  • An abstract class can be interpreted as a class that partially implements an interface and serves as a superclass and interface in one

If during development you start doing @Override to methods implemented in the superclass, most of all if you call super of the same method in the @Override, obviously if there is a cost in performance that is not visible from just look at the subclass code.

Also during the creation of objects it is necessary to take into account that it is necessary while a class is being urged, the constructors of the superclasses must be executed, to guarantee a complete and correct construction of the class in all its functionality, and to build classes if is expensive.

Rather than considerations of performance, the choice between abstract class or interface should be based on the question whether there is code that final classes with high probability are going to have in common, to avoid repetitions and improve maintainability.

    
answered by 12.04.2017 в 02:26