Can I use methods of a class without instantiating this class?

前端 未结 11 2130
执念已碎
执念已碎 2020-12-15 04:10

I have a class with several methods and there is no constructor among these methods.

So, I am wondering if it is possible to call a method of a class without a creat

11条回答
  •  余生分开走
    2020-12-15 04:52

    1) YES, you can use the methods of a class without creating an instance or object of that class through the use of the Keyword "Static".

    2) If you declare the method as "Static" then you can call this method by :

                    *ClassName.MethodName()* 
    

    3) E.g.

    class Hello {
    
       public static void print()
       {
    
         System.out.println("HelloStatic");
       }  
    
    }
    
    
    class MainMethod {
        public static void main(String args[])
        {
           // calling static method
           Hello.print();
        } 
    }  
    

    4) The output of the above program would be : HelloStatic

提交回复
热议问题