Calling a method of a class without creating object of it

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

    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
    
    0 讨论(0)
  • 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;   
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题