Abstract class or interface: JAVA?

I have one common method that I need to use in several classes with only one call to the calling class. So, what I see, I can call it two ways.

public abstract class TestAbstractClass {
    void commonMethod(){
        System.out.println("Calling common method : TestAbstractClass");
    }
}

calling class:

public class RunApplication extends TestAbstractClass{

    public void testMethod(){
        commonMethod();
    }
}

[OR]

Uses the default Java 8 feature in the interface.

public interface TestInterface {
    default void commonMethod(){
        System.out.println("Calling common method : TestInterface");
    }
}

calling class:

public class RunApplication implements TestInterface{

    public void testMethod(){
        commonMethod();
    }
}

They both work great for me, but what works best is an abstract class with a non-abstract method OR An interface with a standard method.

+4
source share
3 answers

Abstract class or interface

If I were you, I will judge the appropriateness by checking whether all these classes are related or not.

, , , , , , .

, .

:

. . , . , , , .

class Bird implements Flyable
{
    @Override
    public void fly(){

    }
}

class Plane implements Flyable
{
    @Override
    public void fly(){

    }
}

, , - . Java . , , .

, .

+1

.

, abstract: .

Java 8 , - :

, .

( ).

, .

, Java 8 default , , , ( , , ).

, , .

" " , , .

+1

Inheritance in any form is intended for use with polymorphism.

If you have a general method, don't just push it to a superclass, but consider using a separate class to wrap it. Thus, you can later use the refactoring code to use the strategy design pattern in case of any fluctuations in the general method.

+1
source

All Articles