#Topic-9
Previous
topic (8) we have discussed about what is Class, Constructors and this keyword
in Java.
If you have not gone through that topic, click this link Class, Constructors and this keyword in Java.
In this section we will discuss about How to use Methods in Java.
Method:
Method is a collection of statements that are grouped
together to perform an operation.
System.out.println() – it is a method, it execute several
statement in order to display a message(internally).
Two types:
1. Methods which
does not return value
2. Methods which have return
value
1. Methods which does not return value:
It must proceeded by void keyword.
2. Methods which return value:
It has 2 types:
a) Methods which have parameters
b) Methods which do not have
parameters
a) Methods which have parameters:
We can avoid
creation of constructor in order to use parameterized method provide values ,We
have to create multiple objects.
Note: Don’t assign any values to parameters variable (not a good practice)
Note: Don’t assign any values to parameters variable (not a good practice)
Example:
Cal c=new Cal();
c.add(10,20);
Cal c1=new Cal();
c1.add(30,40);
b) Methods which do not have parameters
It doesn’t contain any
parameters.
2. Methods which have return value:
Methods can return only one value
at a time; a method can return primitive value, array and object. It must
contain a return statement.
Note: after return() statement should not write anything. If we write
anything after return statement compilation error will occur like un-reachable code.
Method Overloading / compile time
polymorphism.
Method overloading can be
achieved based on differ from the number of parameters, data type of each
parameter and sequence of parameter data type. Method name should be same.
It also called as compile time polymorphism, static binding and early
binding.
Note:
·
Based on the return type we cannot
overload the method.
·
We can overload main method also.
sl.no
|
Java Constructor
|
Java Method
|
1
|
Constructor is used to initialize the state of an object.
|
Method is used to expose behavior of an object.
|
2
|
Constructor must not have return type.
|
Method must have return type.
|
3
|
Constructor is invoked implicitly.
|
Method is invoked explicitly.
|
4
|
The java compiler provides a default constructor if you don't have any
constructor.
|
Method is not provided by compiler in any case.
|
5
|
Constructor name must be same as the class name.
|
Method name may or may not be same as class name.
|
What is Next?
In the next section, we will be going through Call by Value and Call by reference.
If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Twitter or Facebook. Thank you! - Shivananda RaiIn the next section, we will be going through Call by Value and Call by reference.
Comments
Post a Comment