Calling a method of a class without creating object of it

后端 未结 3 1082
梦谈多话
梦谈多话 2021-01-27 09:45
class A{
    String z(){
        System.out.println(\"a\");
        return \"sauarbh\";
    }
}
class B{
    A a;
    A x(){
    return a;   
    }
}
public class runner         


        
3条回答
  •  一生所求
    2021-01-27 10:48

    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.

提交回复
热议问题