Thursday, 10 May 2018


Java Default Method Example

Static Methods inside Java 8 Interface



package java8;

public interface Shape {
           
            default void rectArea(float l,float w)
            {
                        System.out.println("AreaofRectangle="+(l*w));
            }
           
            public static void staticMethod()
            {
                        System.out.println("we can declared inside interface static and default method in jdk 8");
            }
           
           
            public void area();

}


package java8;

import java.util.Scanner;

public class Circle implements Shape{

            @Override
            public void area() {
                        float r;
                        System.out.println("enter radius");
                        Scanner s1=new Scanner(System.in);
                        r=s1.nextFloat();
                        System.out.println("Area of circle="+(3.14f*r*r));
            }
}


import java.util.Scanner;

public class Triangle  implements Shape{
           
            public void area() {
                        float a,b;
                        System.out.println("enter a and b value");
                        Scanner s1=new Scanner(System.in);
                        a=s1.nextFloat();
                        b=s1.nextFloat();
                        System.out.println("Area of Triangle="+(0.5f*a*b));
            }

}
package java8;

public class ShapeMain {
            public static void main(String[] args) {
                        Circle c1=new Circle();
                        Triangle t1=new Triangle();
                        c1.area();
                        t1.area();
                        c1.rectArea(4.5f, 4.5f);//calling default method of interface
                        Shape.staticMethod();//calling static method of interface
            }

}



o/p:-----------------------------------
enter radius
3
Area of circle=28.26
enter a and b value
2
3
Area of Triangle=3.0
AreaofRectangle=20.25
we can declared inside interface static and default method in jdk 8


No comments:

Post a Comment