Interface Default and Static Methods
Normally all the interface methods are by default abstract, implementations of those methods in the classes that implement the interfaces.
Java 8 Provides to support default and static methods. A default method is an instance method defined in an interface whose method header begins with the default keyword; it also provides a code body. Every class that implements the interface inherits the interface's default methods and can override them.
Program on Default methods
interface abc
{
default public void put(int x,int y)
{
System.out.println("Sum of2 nos "+(x+y));
}
}
class xyz implements abc
{
public void put1(int x,int y)
{
System.out.println("Sub traction "+(x-y));
}
}
public class inter1 {
public static void main(String[] args) {
xyz x=new xyz();
x.put(20, 40);
x.put1(45, 2);
}
}
Program on Default interface to print the address
interface address
{
String getStreet();
String getCity();
default String getFullAddress()
{
return getStreet()+", "+getCity();
}
}
class fuladdress implements address
{
private String street;
private String city;
private String name;
public fuladdress(String na,String street, String city)
{
name=na;
this.street = street;
this.city = city;
}
public String getName()
{
return name;
}
public String getCity()
{
return city;
}
public String getStreet()
{
return street;
}
}
public class inter2
{
public static void main(String[] args)
{
fuladdress x=new fuladdress("Prasad","MainRoad","Vuyyuru");
System.out.println("Name :"+x.getName());
System.out.println("Street:"+x.getStreet());
System.out.println("City: "+x.getCity());
System.out.println("Ful address "+x.getFullAddress());
}
}
Default Multiple Methods
If the class implements two or more interfaces that define the same default method, Java will throw a compilation error. You will need to override the method and choose from one of the methods.
Programe on multiple default interface methods
interface rose
{
default void putflower()
{
System.out.println("Rose Flower....");
}
}
interface jasmine
{
default void putflower()
{
System.out.println("Jasmine Flower...");
}
}
class flowers implements rose,jasmine
{
public void putflower()
{
rose.super.putflower(); // calls rose putflower
jasmine.super.putflower(); // calls jasmine putflower
System.out.println("Rose and Jasmine flowers...");
}
}
public class interf4 {
public static void main(String[] args) {
flowers x=new flowers();
x.putflower();
}
}
Program on Static Methods in interfaces
interface abc1
{
static void put(int x,int y)
{
System.out.println("Sum of 2nos "+(x+y));
}
}
class xyz1 implements abc1
{
public void put1(int x,int y)
{
System.out.println("Sub traction "+(x-y));
}
}
public class inter3 {
public static void main(String[] args)
{
xyz1 k=new xyz1();
//k.put(32,22); // not acessable
k.put1(43, 22);
abc1.put(43,3);
//xyz1.put(44,3);// not acessable
}
}
For
Online Classes
Contact Us: 9885348743
Online Classes
Contact Us: 9885348743