Java Classes Introducing Methods
Introducing Methods:
Classes usually consist of two things: Instance Variables and Methods. The general form of a method:
type name (parameter-list) {
body of method
}
type
specifies the type of data returned by the method. This can be valid
type, including class types that you create. If the method does not
return a value, its return type must be void. The name of the method is
specified by name. It is a legal identifier other than used by other
items within current scope. The parameter-list is a sequence of type and
identifier pairs separated by commas. If the method has no parameter,
then the parameter list will be empty.
Methods
that have a return type other than void return a value to the calling
routine using the following form of the return statement:
return value;
value is the value returned.
Java Program Showing Use of class having method and returns a value by Asad Hussain:
/*
This is Java Program Showing Use of class having method and returns a value.
Program developed by #Asad Hussain
This file name is "Returnmethod.java".
*/
import java.util.*;
class Rectangle {
double width;
double length;
double area() {
return length * width;
}
}
public class Returnmethod{
public static void main(String args[]){
Rectangle myrectangle1 = new Rectangle();
Rectangle myrectangle2 = new Rectangle();
double area;
myrectangle1.width = 25;
myrectangle1.length = 35;
myrectangle2.width = 45;
myrectangle2.length = 95;
area = myrectangle1.area();
System.out.println("Area is " + area);
area = myrectangle2.area();
System.out.println("Area is " + area);
}
}
This is Java Program Showing Use of class having method and returns a value.
Program developed by #Asad Hussain
This file name is "Returnmethod.java".
*/
import java.util.*;
class Rectangle {
double width;
double length;
double area() {
return length * width;
}
}
public class Returnmethod{
public static void main(String args[]){
Rectangle myrectangle1 = new Rectangle();
Rectangle myrectangle2 = new Rectangle();
double area;
myrectangle1.width = 25;
myrectangle1.length = 35;
myrectangle2.width = 45;
myrectangle2.length = 95;
area = myrectangle1.area();
System.out.println("Area is " + area);
area = myrectangle2.area();
System.out.println("Area is " + area);
}
}
Output of this Program:
Java Program Showing Use of class having method and returns a value by Asad Hussain |
Post a Comment