Menu

Showing posts with label Use of Interface. Show all posts
Showing posts with label Use of Interface. Show all posts

Java Interface examples

In this blog we will see different ways of implement interface in Java.

For example we have two interfaces, IntOne and IntTwo as below.

interface IntOne {
    public String getSrc();
}

interface IntTwo {
    public String getName();
}

1. Simple one and one implements example of interface

class IntOneImpl implements IntOne {
    private String src = "Source Interface One";
    
    public String getSrc() {
        return src;        
    } 
}

class IntTwoImpl implements IntTwo {
    private String name = "Java Interface Examples";
    
    public String getName(){
        return name;
    }
    
}

public class Main
{
public static void main(String[] args) {
IntTwoImpl in = new IntTwoImpl();
IntOneImpl one = new IntOneImpl();
System.out.println(one.getSrc());
System.out.println(in.getName());
}
}

This will work fine and give you output 
Source Interface One
Java Interface Examples

2. Lets see if we implement both the interfaces in a single class and access their methods.


class IntOneImpl implements IntOne {
    private String src = "Source Interface One";
    
    public String getSrc() {
        return src;        
    } 
}

class IntTwoImpl implements IntOne, IntTwo {
    private String name = "Java Interface Examples";
    IntOneImpl intOne = new IntOneImpl();
    @Override
    public String getSrc() {
        return intOne.getSrc();
    }
    
    @Override
    public String getName(){
        return name;
    }
    
}

public class Main
{
public static void main(String[] args) {
IntTwoImpl in = new IntTwoImpl();
System.out.println(in.getSrc());
System.out.println(in.getName());
}
}

Lets see what is happeing in this code.

a. IntOneImpl implements the IntOne and provide definition of getSrc method.

b. IntTwoImpl implements IntOne and IntTwo interfaces and override methods from both the interfaces.