Calling a method of a class without creating object of it

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

提交回复
热议问题