Calling a method of a class without creating object of it

后端 未结 3 1088
梦谈多话
梦谈多话 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:37

    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;   
        }
    }
    

提交回复
热议问题