How I can call static method without creating object of class?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How I can call static method without creating object of class??

I try to call static method in class call (car)..the static method call (horn)..I type that in main car.horn (); but it's give me wrong... as I understand static method can call without creating opject of class isn't true? !

9th Aug 2016, 3:40 PM
Islam Elzohary
Islam Elzohary - avatar
3 Answers
+ 2
Alright, just an fyi, it's very difficult to help people who don't post code, I have to assume your problem without actually knowing what it is. First, capitalize your class names, thats just proper Java etiquette. Second, yes you can call static methods without instantiating, problem here, is you didn't tell us what error you got. Based on what you've said, it should work no problem. Error is on your end somewhere. If I were to throw out a random guess, maybe method is just named static horn() and error says you need a return type? If I got lucky, and that's your error, it should have void, static void horn(){}
9th Aug 2016, 4:08 PM
James
James - avatar
0
sorry for not type code..I will notice to type it in question next time. .and thx for replay retest the code and it's work good
9th Aug 2016, 5:29 PM
Islam Elzohary
Islam Elzohary - avatar
0
Having a method static means that it inherently doesn't need an object to access it, it can be statically be accessed (given the access modifier is allows for access). Using the dot operator ClassName.myStaticMethod() you can access the method. Be sure that if you are to call a static method you need to call it from a static method. A good example is the main method, it's static so that the class with the main method needn't be instantiated to call the main method, it is statically (during complie time) defined and resources allocated therefore no need to be instantiated at runtime.
10th Aug 2016, 2:41 AM
Eric Gitangu
Eric Gitangu - avatar