-4

Actually am new to Java,How to call one class1 from another class2? Class1 has main() and other methods.Class2 has different methods. I want to call class1 from Class2. Please provide the syntax.

Karthik Bs
  • 1
  • 1
  • 4
  • 1
    Welcome to Stack Overflow. You need to post your code in order for us to be able to help you. – Michael Nov 07 '17 at 10:40

3 Answers3

0

You need to first create an object of type class2 and call the methods of it from main method of class1.

class2 c = new class2();
c.methodOfClass2();
0

Say you have the following classes:

public class A {
   int a1 = 15;

   public void showMessage() {
         System.out.println("Hey!");
     }
}

public class B {

}

In case you want your class B to be able to read a1 and call showMessage(), you need to create an object of the class they belong, in the class you'll be working in. Like this:

public class A {
   int a1 = 15;

   public void showMessage() {
         System.out.println("Hey!");
     }
}

public class B {
     public static void main(String[] args) {
           A a = new A();
           //call either variables or methods by putting 
           //a. in front of them
     }
}
Luis Eduardo
  • 47
  • 1
  • 11
0

To call methods of Class1 from Class2

  1. If static method, call by className. e.g - Class1.staticMethodToBeCalledFromClass2();
  2. If non-static method, you need to create object of Class1. e.g - Class1 cls1 = new Class1(); cls1.nonStaticMethodToBeCalledFromClass2();

Assuming Your code :

public class Class1{
        public static void main(String[] args) {

        }

        public void nonStaticMethodTobeCalledFromClass2() {

        }

        public static void staticMethodTobeCalledFromClass2() {

        }
    }

    public class Class2 {
        public void callClass1Here() {
            Class1 cls1 = new Class1();
            cls1.nonStaticMethodTobeCalledFromClass2();

            Class1.staticMethodTobeCalledFromClass2();
        }
    }

If you look at the code, you will see, to call