class A{
String z(){
System.out.println(\"a\");
return \"sauarbh\";
}
}
class B{
A a;
A x(){
return a;
}
}
public class runner
To call:
String z(){
System.out.println("a");
return "sauarbh";
}
without the object of the class A
the method z
has to be static:
static String z(){
System.out.println("a");
return "sauarbh";
}
So change your code as following:
class A{
static String z(){
System.out.println("a");
return "sauarbh";
}
}
class B{
A a;
A x(){
return a;
}
}
public class runner {
public static void main(String[] args) {
B b = new B();
b.x();
A.z();
}
}
Output :
a
Class B method x()
is not returning new object of A. Instead you are returning object of Class A with null value.
A a; // value of a is null
A x() {
return a;
}
In runner class
A a2=b.x(); // b.x() will return a, which is null. so A a2=null
a2.z(); // Equivalent to null.z() throws NullPointerException
Make below changes in your Class B
code:
class B{
A a;
A x(){
return new A();// return new object of Class A;
}
}
or
class B{
A a= new A(); // Initialize Class A with new object
A x(){
return a;
}
}
Yes without instantiate the class if you want to call the method you should use static
key word.
What are you doing here?
You are indirectly try to get instance of A
. But this case you will get NullPointerException
since you just return only a reference(variable) of A
B b = new B();
A a2=b.x();
a2.z(); // NullPointerException from here
NPE?
class B{
A a;
A x(){
return a; // you just return the reference
// it should be return new A();
}
}
For your edit:
Take a look at insert()
method. It is creating Person
instance.