Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What are the differences between abstract classes and interfaces in Java 8?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 166
    Comment on it

    Difference between abstract class and interface in Java 8 :

    1. To create abstract classes we use the 'abstract' keyword whereas keyword 'interface' is used to make the interfaces in Java.
    2. For inheritance the 'extends' keyword is used by the subclasses whereas 'implements' keyword is used to implement the interface into the subclasses and should implement all the methods declared inside the interface.
    3. We can create constructors inside the abstract method, but not in interface.
    4. Java interface can have public methods by default while abstract class can have any of public, private, and protected members.
    5. An interface can extend only one interface but an abstract class can extends one abstract class and implement multiple interfaces.
    6. We can not run the interface Java class but we can run abstract class in it contains the main() method.

    Note: According the Java7 specification the main difference between abstract class and interface was that the abstract class can have abstract methods and methods with implementation whereas interface only contains abstract methods. But as per Java 8 specification this difference is removed means interface can contain the method with implementation. Interface can define default and static methods with implementation code.

    For example:

    SampleInterface.java

    package com.sample.java8;
    
    public interface SampleInterface {
    
        default void show(String value) {
                System.out.println("SampleInterface Print::" + value);
        }
    }
    

    SampleInterfaceImpl.java

    package com.sample.java8;
    
    public class SampleInterfaceImpl implements SampleInterface {
    
        public boolean isValueNull(String value) {
            System.out.println("Null Checking");
    
            return value == null ? true : false;
        }
    
        public static void main(String args[]){
            SampleInterfaceImpl object = new SampleInterfaceImpl();
            object.show("This is interface method.");
            object.isValueNull("Check");
        }
    }
    

    Output :

    SampleInterface Print:: This is interface method.
    False
    

    In the above example you can see that we have defined an interface called 'SampleInterface' having a method show() with the implementation.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: