- Modifier(Public/private) method declaration must be start with this component.
- Return type its necessary part of an method if method does not have any return type then void should be used.
- MethodName Programmer can use any name for method accept ut can not be reserved keyword or name of method should not be same with class name.
- ParameterList After name of method input parameter list should be defined in () seperated by comma with their data types if their is no input data () must be empty.
- Exception list is to be define that throws by a method this part is optional depending upon situation of program.
- Braces({}) without this part program will not compile this is an necessary part of an method.
EXAMPLE OF SIMPLE METHOD IN JAVA:
class current
{
double current;
double resistance;
public void display()
{
System.out.println("current="+current);
System.out.println("resistance="+resistance);
System.out.println("voltage="+resistance*current);
}
}
class voltage
{
public static void main(String args[])
{
//Creating Object Of current
current cur=new current();
//assiging value of current and resistance in instance variablecur.current=3;
cur.resistance=100;
cur.current=10;
//calling method to display voltage
cur.display();
}
}
}
EXPLANATION:
EXAMPLE OF METHOD THAT TAKES PARAMETER:
class current
{
double current;
int resistance;
public void display(double cur,int resis)
{
current=cur;
System.out.println("current="+current);
resistance=resis;
System.out.println("resistance="+resistance);
System.out.println("voltage="+resistance*current);
}
}
class voltage
{
public static void main(String args[])
{
//Creating Object Of current
current x=new current();
//calling method
x.display(50,5);
}
}
0 comments:
Post a Comment