Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Interface with default methods vs Abstract class in Java 8

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 328
    Comment on it

    Interface with default methods in Java 8

    In later version of Java Interfaces always contained only method declaration. We are not giving method definition in the interfaces because java did not allow multiple inheritance of classes. But in Java 8 it is now possible to add method definitions in interfaces.

    Java 8 has a additional feature called Default Methods. Now using this method we can add method definitions into interfaces. The below code will show you how to add default method in interface.

    public interface Demo {
        default void foo(){
           System.out.println("Calling A.foo()");
        }
    }
    
    public class Main implements Demo {
    
        public static void main(String ss[])
        {
            Demp d=new Main();
            d.foo(); 
        }
    }
    

    Abstract class

    The abstract classes allow us to declare the non-final variables, non-static methods, and allow to put modifiers in method like public, protected, default. We can also define the non abstract method but in case of interface the variables are final, all the methods are public and static by default. We can not give definition of any method But in Java 8 we give the body of default method.

    abstract class Demo
    {
        public abstract void disp();
    
        public show()
        {
            System.out.println(Non abstract method);
        }
    }
    public class Demo1 extends Demo
    {
        public void disp()
        {
            System.out.println(Implementation of disp);
        }
        public static void main(String ss[])
        {
            Demo demo=new Demo1();
            demo.show();
        }
    }
    

 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: