简体   繁体   English

java从另一个调用类中的一个函数

[英]java-call a function in a class from another one

class A: A类:

public class A extends Activity{
    B b;

    @Override
    public void onCreate(Bundle savedInstanceState) {
       b.sample();
    }

    public void test(){
       //Do Something
    }
}

Class B: B级:

public class B{

    public void sample(){
       //Do Something
    }
}

Its Ok To call methods Of Class B in the Class A, But How Is it Possible to Call Class A methods And Functions In Class B? 可以在A类中调用B类的方法,但是如何在B类中调用A类的方法和函数呢?

I cant create An New Object Of Class A in Class B like: 我无法在B类中创建A类的新对象,例如:

A a = new A();

because It then Creates A Whole New Activity (Am I Right?!) 因为它随后创建了一个全新的活动(我对吗?!)

Should I Use Interface to Achieve this? 我应该使用界面来实现这一目标吗?

define the B constructor and make it receive the activity 定义B构造函数并使其接收活动

public class B{
   private Activity theActivityA;
   B(Activity activitiy){
    this.theActivityA = activitiy;
   if(this.theActivityA!=null){
      this.theActivityA.test();
   }
}

Yes, you can use interfaces. 是的,您可以使用界面。 I assume that you need to notify the activity about something. 我假设您需要通知活动某些事情。

public class A extends Activity implements B.IListener {
....

public class B{
    IListener mListener;
    B(IListener listener){
        mListener=listener;
    }
    public void sample(){
       //Do Something
    }
    public interface IListener {
       something();
    }
}

So, in B you can call methods to any instance of IListener, not just A. 因此,在B中,您可以调用方法到IListener的任何实例,而不仅仅是A。

Hope it helps. 希望能帮助到你。

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

相关问题 无法从另一个Java类调用函数 - Unable to call function from another java class Java:使用actionlistener在该类的对象上调用另一个类中的函数 - Java: Using an actionlistener to call a function in another class on an object from that class Java代码不允许我从一个类到另一个类调用方法 - Java code is not letting me call a method from one class to another 如何在Java中将字符串值从一个类调用到另一个类 - How to call String value from one class to another in Java 如何从另一个类及其上下文中调用函数(Android,Java) - How to call a function from another class with its context (android, java) 调用从一个类到另一个类的getconnection方法的Java命令 - java command to call a getconnection method from one class to another 如何在Java(Android)中将变量的值从一个类调用到另一个类 - How to call the value of variables from one class to another in Java (Android) 如何在Java中从一个类调用方法到另一个 - How do i call a method in Java from one class to another 如何使用onClick从一个文件类调用函数到另一个文件? - How to call function from one file class to another file with onClick? 从另一个类调用函数 - Call a function from another class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM