shariful islam
shariful islam

Reputation: 399

Java : How to pass data from one class to another using interface?

We know java can extends with only one class. In this case I want to do the bellow work using interface.

MainClass.java

public class MainClass extends Mango {
    public static void main(String[] args) {
        MainActivity over = new MainActivity();
        over.run();
    }

    public void run(){
        one();
    }

    @Override
    public void two(String s){
        System.out.println("result : "+s);
    }
}

Mango.java

public class Mango {
    public void one(){
        System.out.println("mango one");
        two("mango two");
    }
    public void two(String s){}
}

Output :

mango one
result : mango two

The Problem :

In this case I got result : mango two by extending MainClass with Mango. But in my project the MainClass already extends with another class. That's why I want to use an interface that I will implements with MainClass for Override method two() of Mango class

as if I can receive data from Mango class

How can I do that?

Upvotes: 0

Views: 6434

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40078

Yes you can achieve this by using Interface, in jdk8 you can declare default and static methods and not mandatory to override in child class

public interface MongoSample {

default void one(){
    System.out.println("mango one");
    two("mango two");
}
default void two(String s){}

}

Main Class

public class MainClass implements MongoSample {

public static void main(String[] args) {
    MainClass over = new MainClass();
    over.run();
}

public void run(){
    one();
}
@Override
public void two(String s){
    System.out.println("result : "+s);
}

}

output:

mango one
result : mango two

Upvotes: 1

Related Questions