The
general form of a method is as follows:
type
methodname(parameter-list) {
//body
of the method.
}
o type specifies
the type of data returned by method. Ifmethod does not return any value then type should be void.
o The
methodname specifies the name of the
method.
o The
parameter-list is a sequence of type
and identifier pairs separated by commas.
Ex:class
Myclass {
int
a;
int b;
void Getdata(int x,int y) { //Method with
parameters.
a=x;
b=y;
}
void Display() {
//Method with no parameters.
System.out.println
(“A= “ +a+ “ B= “+b);
}
int sum() { //Method
that return some value.
return(a+b);
}
}
class
Mymain {
public static void main(String args[]) {
Myclass c1=newMyclass();
c1.Getdata(10,20);//Accessing
method
Myclass
c2=new Myclass();
c2.a=30;//
Accessing Member variables
c2.b=40;
c1.Display();
int
sum=c2.sum();
System.out.
print("\n Sum of Second object is:"+sum);
}
}
Output:
A= 10 B= 20
Sum of Second object is: 70
No comments:
Write comments