Java class methods
Contents
Introducing Methods in Java Class : Class Concept in Java
- In Java Class , We can add user defined method.
- Method is equivalent to Functions in C/C++ Programming.
Syntax : Methods in Java Classes
return_type method_name ( arg1 , arg2 , arg3 )
- return_type is nothing but the value to be returned to an calling method.
- method_name is an name of method that we are going to call through any method.
- arg1,arg2,arg3 are the different parameters that we are going to pass to a method.
Return Type of Method :
- Method can return any type of value.
- Method can return any Primitive data type
int sum (int num1,unt num2);
- Method can return Object of Class Type.
Rectangle sum (int num1,unt num2);
- Method sometimes may not return value.
void sum (int num1,unt num2);
Method Name :
- Method name must be valid identifier.
- All Variable naming rules are applicable for writing Method Name.
Parameter List :
- Method can accept any number of parameters.
- Method can accept any data type as parameter.
- Method can accept Object as Parameter
- Method can accept no Parameter.
- Parameters are separated by Comma.
- Parameter must have Data Type
Live Example : Introducing Method in Java Class
class Rectangle { double length; double breadth; void setLength(int len) { length = len; } } class RectangleDemo { public static void main(String args[]) { Rectangle r1 = new Rectangle(); r1.length = 10; System.out.println("Before Function Length : " + r1.length); r1.setLength(20); System.out.println("After Function Length : " + r1.length); } }
Output :
C:Priteshjava>java RectangleDemo Before Function Length : 10.0 After Function Length : 20.0
Explanation :
Calling a Method :
- “r1” is an Object of Type Rectangle.
- We are calling method “setLength()” by writing -
Object_Name [DOT] Method_Name ( Parameter List ) ;
- Function call is always followed by Semicolon.
Method Definition :
- Method Definition contain the actual body of the method.
- Method can take parameters and can return a value.