Passing a method from another class

后端 未结 4 502
渐次进展
渐次进展 2020-12-22 03:09

I want to call a method from one class to another, don\'t know if that\'s possible without extends the class that contains the method. I\'ve tried to import the package, tha

相关标签:
4条回答
  • 2020-12-22 04:02

    You need an instance of object from class 1 to invoke that method, or if it doesn't need an instance - you can declare it as static and then you can write 1.method().

    0 讨论(0)
  • 2020-12-22 04:03

    If you want to call the method without creating an instance of the class then make it static:

    Class1
    {
    ...
        public static void method1() {doSomething;}
    }
    
    Class2
    {
        public class2()
        {
            Class1.method1(); //should be fine
        }
    }
    

    edit: If you want to pass data between Activities that is slightly different. Generally you do something like startActivityForResult() and then retrieve the return value, or use Intents like so:

    How do I pass data between Activities in Android application?

    0 讨论(0)
  • 2020-12-22 04:08

    In java you 2 main ways to do that:

    1. Class2 extends Class1 and then you can call all protected or public methods of class 1.
    2. Get an instance of class1 inside class2:

      Class1 c1 = new Class1();
      c1.someMethod();
      
    0 讨论(0)
  • 2020-12-22 04:09

    Other way may be, create object for other class and then invoke the method on that object. Something like below.

    new ClassA().yourMethod();
    
    0 讨论(0)
提交回复
热议问题