简体   繁体   English

Java:如何使用接口将数据从一类传递到另一类?

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

We know java can extends with only one class. 我们知道Java只能extends一个类。 In this case I want to do the bellow work using interface . 在这种情况下,我想使用interface做下面的工作。

MainClass.java 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 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 . 在这种情况下,我得到了结果:Mango 扩展 MainClass来实现芒果二 But in my project the MainClass already extends with another class. 但是在我的项目中, MainClass已经扩展了另一个类。 That's why I want to use an interface that I will implements with MainClass for Override method two() of Mango class 这就是为什么我要使用将与MainClass 实现接口用于Mango类的Override方法two()的原因

as if I can receive data from Mango class 好像我可以从芒果班接收数据

How can I do that? 我怎样才能做到这一点?

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 是的,您可以使用Interface实现此目的,在jdk8中,您可以声明defaultstatic方法,而不必在子类中重写

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM