Explained easily | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Explained easily

so if i understand correctly in the above example, a static method can be called by a class name so in the above example vehicle.horn(); would also work? without the static one would have to create An object vehicle v1 and use that object to call the method like v1.horn();

23rd Nov 2016, 1:25 PM
Dirk
Dirk - avatar
2 Answers
+ 4
Exactly. Non-static methods need an instance of the given class to call upon, like: Object o = new Object(); o.getClass(); //Not like: Object.getClass(); While static methods can be called on the class itself, like: String.format(...); //Not like: //String s = "example"; //s.format(...); Non-static methods can access the instance they are called upon like: void NotStatic() { Object instace = this; } While the 'this' keyword cannot be used in static methods, because there is no instance the method is called on.
23rd Nov 2016, 2:02 PM
Magyar Dávid
Magyar Dávid - avatar
+ 2
if this is the case they used the wrong example to make this clear in the above lesson...
23rd Nov 2016, 1:26 PM
Dirk
Dirk - avatar