Java static method program: static methods in Java can be called without creating an object of class. Have you noticed why we write static keyword when defining main it's because program execution begins from main and no object has been created yet. Consider the example below to improve your understanding of static methods.
Java static method example program
Output of program:
Java static method vs instance method
Instance method requires an object of its class to be created before it can be called while static method doesn't require object creation.
Output of code:
Using static method of another classes
If you wish to call static method of another class then you have to write class name while calling static method as shown in example below.
Output of program:
Here we are using min and max methods of Math class, min returns minimum of two integers and max returns maximum of two integers. Following will produce an error:
We need to write class name because many classes may have a method with same name which we are calling.
No comments:
Post a Comment