Reputation: 83
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
Upvotes: 0
Views: 229
Reputation: 344
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.
Upvotes: 0
Reputation: 110
You should "new" your class first.
Private Class1 class1 = new Class1();
Upvotes: 0
Reputation: 276306
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
Upvotes: 2