简体   繁体   中英

How to call Method in another class to the other class and pass it to main

How to call method in another class to other class and pass it to main class

i have Class1.java class that looked like this

public class Class1{

    public void callMe() {
        System.out.println("Menambah tabel mahasiswa");
    }

}

Then I create another class named Class2 in a file called Class2.java that looked like this

public class Class2 {

    private Class1 class1;

    //getset generated by netbeans, skipped

    public void justCallMe(){
        class1.callMe();
    }
}

and i want to use the class2 method named justCallMe() in main class, that looked like this

    Class2 classy = new Class2();
    classy.justCallMe();

but it give me error "java.lang.NullPointerException" I think it cause by wrong passing method from class to class and to main, cause when i try invoke System.out.println("test") ; in Class2 , it worked

There are several things wrong with your code.

First of all,

Class2 classy = new classy();

Should be

Class2 classy = new Class2();

Since you're creating an instance of Class2

Second of all, in the constructor, you need to initialize its Class1 member, so inside Class2 you need a constructor that'll do that for you

public Class2() {
   class1 = new Class1();
}

The NullPointerException you received is probably because in your real code you did have Class2 classy = new Class2(); but did not initialize its class1 member

Your error is here:

Class2 classy = new **classy**();

It should be:

Class2 classy = new **Class2**();

And yes, also initialize class1 inside class2.

你应该首先“新”你的班级。

Private Class1 class1 = new Class1();

Your code contains many errors. To better understand see the following source code.

First, create a sub class

class subclass {
         //Create a method to be called .Here the name is used as Meth

         public void Meth(){
         //Do some work here
         }

Then, create a super class containing main method.

    class superclass {
           public static void main(String ar[]){
           //Create an object of sub class
           subclass subc = new subclass();
           //To call function to execute its task
           subc.Meth();
}

If the sub class is in another package then import that class of that package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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