Home

Using the Methods of a Class

 

Methods' Arguments

 

Introduction

A method performs an assignment that completes the operations of a class. The methods we used in the previous sections relied on local variables to exchange information with other sections of the program. Sometimes, a method would need one or more values in order to carry its assignment. The particularity of such a value or such values is that another method that calls this one must supply the needed value(s). When a method needs a value to complete its assignment, such a value is called an argument.

Like a variable, an argument is represented by its type of value. For example, one method may need a character while another would need a string. Yet another method may require a decimal number. This means that the method or class that calls a method is responsible for supplying the right value, even though a method may have an mechanism of checking the validity of such a value.

The value supplied to a method is typed in the parentheses of the method and it is called an argument. In order to declare a method that takes an argument, you must specify its name and the argument between its parentheses. Because a method must specify the type of value it would need, the argument is represented by its data type and a name.

Suppose you want to define a method that displays the side length of a square. Since you would have to supply the length, you can start the method as follows:

public class Exercise {

    static void displaySide(double length) {
    }
}

In the body of the method, you may or may not use the value of the argument. Otherwise, you can manipulate the supplied value as you see fit. In this example, you can display the value of the argument as follows:

public class Exercise {

    static void displaySide(double length) {
	System.out.print("Length: " + length);
    }
}

When calling a method that takes an argument, you must supply a value for the argument; otherwise you would receive an error. Also, you should/must supply the right value; otherwise, the method may not work as expected or it may produce an unreliable result. Here is an example:

public class Exercise {

    static void displaySide(double length) {
	System.out.print("Length: " + length);
    }

    static void main(String[] args) {
	displaySide(35.55);
    }
}

As mentioned already, a method that takes an argument can also declare its own local variable(s). A method can take more than one argument. When defining such a method, provide each argument with its data type and a name. The arguments are separated by a comma.

Practical LearningPractical Learning: Passing Arguments

  1. Start NetBeans
  2. Create a New Project as a Java Application and name it Geometry2
  3. In the Projects window, under Geometry2, expand Sources Packages if necessary.
    To create a new class, under the Geometry2 folder, right-click the Geometry2 sub-folder -> New -> Java Class...
  4. Set the Name to Cylinder and click Finish
  5. Change the file as follows:
    package geometry2;
    import java.util.Scanner;
    
    public class Cylinder {
        double specifyRadius() {
            double rad;
            Scanner scnr = new Scanner(System.in);
    
            System.out.print("Radius: ");
            rad = scnr.nextDouble();
    
            return rad;    
        }
    
        double specifyHeight() {
            double h;
            Scanner scnr = new Scanner(System.in);
    
            System.out.print("Height: ");
            h = scnr.nextDouble();
    
            return h;
        }
    
        double calculatebaseArea(double rad) {
            return rad * rad * 3.14159;
        }
    
        double calculateLateralArea(double rad, double hgt) {
            return 2 * 3.14159 * rad * hgt;    
        }
    
        double calculateTotalArea(double rad, double hgt) {
            return 2 * 3.14159 * rad * (hgt + rad);
        }
    
        double calculateVolume(double rad, double hgt) {
            return 3.14159 * rad * rad * hgt;
        }
    
        void process() {
            double radius;
            double height;
            double baseArea;
            double lateralArea;
            double totalArea;
            double volume;
            
            System.out.println("Enter the dimensions of the cylinder");
            radius = specifyRadius();
            height = specifyHeight();
    
            baseArea = calculatebaseArea(radius);
            lateralArea = calculateLateralArea(radius, height);
            totalArea = calculateTotalArea(radius, height);
            volume = calculateVolume(radius, height);
    
            System.out.println("\nCylinder Characteristics");
            System.out.printf("Radius:  %g\n",  radius);
            System.out.printf("Height:  %g\n",  height);
            System.out.printf("Base:    %f\n", baseArea);
            System.out.printf("Lateral: %f\n", lateralArea);
            System.out.printf("Total:   %f\n", totalArea);
            System.out.printf("Volume:  %f\n", volume);  
        }
    }
  6. Access the Main.java file and change it as follows:
    package geometry2;
    
    public class Main {
        static void main(String[] args) {
            Cylinder cyl = new Cylinder();
    
            cyl.process();
        }
    }
  7. Execute the application to test it. Here is an example:
    Enter the dimensions of the cylinder
    Radius: 35.95
    Height: 30.25
    
    Cylinder Characteristics
    Radius:  35.9500
    Height:  30.2500
    Base:    4060.198770
    Lateral: 6832.879710
    Total:   14953.277250
    Volume:  122821.012792

Passing an Argument by Value

When calling a methods that takes one or more arguments, we made sure we provided the necessary value. This is because an argument is always required and the calling method must provide a valid value when calling such a method. This technique is referred to as passing an argument by value.

Method Overloading

A typical program involves a great deal of names that represent variables and methods of various kinds. The compiler does not allow two variables to have the same name in the same method. Although two methods should have unique names in the same program, a class can have different methods with the same name if you follow some rules. The ability to have various methods with the same name in the same program is referred to as method overloading. To perform overloading, the methods must have different numbers or different type(s) of arguments.

The moment of inertia is the ability of a beam to resist bending. It is calculated with regard to the cross section of the beam. Because it depends on the type of section of the beam, its calculation also depends on the type of section of the beam. In this exercise, we will review different formulas used to calculate the moment of inertia. Since this exercise is for demonstration purposes, you do not need to be a Science Engineering major to understand it.

Practical LearningPractical Learning: Overloading a Method

  1. Start a new Java Application named MomentOfInertia1
     
    The Moment Of Inertia
  2. Change the file as follows:
    package momentofinertia1;
    import java.util.Scanner;
    
    public class Main {
        // Rectangle
        static double calculateMomentOfInertia(double b, double h) {
    	return b * h * h * h / 3;
        }
        
        static void main(String[] args) {
            double base, height;
            Scanner scnr = new Scanner(System.in);
    	
    	System.out.println("Enter the dimensions of the Rectangle");
    	System.out.print("Base:    "); 
    	base = scnr.nextDouble();
    	System.out.print("Height: ");
    	height = scnr.nextDouble();
    	
    	System.out.println("\nMoment of inertia with " +
    			  "regard to the X axis: ");
    	System.out.printf("I = %.2fmm", 
    			  calculateMomentOfInertia(base, height));
        }
    }
  3. Execute the application. Here is an example of running the program:
    Enter the dimensions of the Rectangle
    Base:    
    2.44
    Height: 
    3.58
    
    Moment of inertia with regard to the X axis: 
    I = 37.317939mm
  4. A circle, and thus a semi-circle, requires only a radius. Since the other version of the calculateMomentOfInertia() function requires two arguments, we can overload it by providing only one argument, the radius.
    To overload the above calculateMomentOfInertia() method, type the following in the file:
     
    The Moment of Inertia for a Circle
    package momentofinertia1;
    import java.util.Scanner;
    
    public class Main {
        // Rectangle
        static double calculateMomentOfInertia(double b, double h) {
    	return b * h * h * h / 3;
        }
    
        // Semi-Circle
        static double calculateMomentOfInertia(double R) {
    	final double PI = 3.14159;
    	
    	return R * R * R * R * PI/ 8;
        }
        
        static void main(String[] args) {
    	double radius;
            double base, height;
            Scanner scnr = new Scanner(System.in);
    	
    	System.out.println("Enter the dimensions of the Rectangle");
    	System.out.print("Base:    "); 
    	base = scnr.nextDouble();
    	System.out.print("Height: ");
    	height = scnr.nextDouble();
    	
    	System.out.println("\nMoment of inertia with " +
    			  "regard to the X axis: ");
    	System.out.printf("I = %fmm", 
    			  calculateMomentOfInertia(base, height));
            
    	System.out.print("\nEnter the radius: ");
    	radius = scnr.nextDouble();
    	
            System.out.println("Moment of inertia of a semi-circle " +
    			  "with regard to the X axis: ");
    	System.out.printf("I = %fmm", calculateMomentOfInertia(radius));
        }
    }
  5. Execute the program. Here is an example:
     
    Enter the dimensions of the Rectangle
    Base:    
    4.25
    Height: 
    2.55
    
    Moment of inertia with regard to the X axis: 
    I = 23.490281mm
    Enter the radius: 
    5.35
    Moment of inertia of a semi-circle with regard to the X axis: 
    I = 321.717472mm
  6. Here are the formulas considered for a triangle:

    Inertia

    As you can see, the rectangle and the triangle are using the same dimension types. This means that we can provide only the same kinds of arguments, the base and the height, to calculate the moment of inertia. This also means that the compiler will not allow us to write two methods that have the same name, the same number of arguments, and the same types of arguments because that would violate the rule of function overloading.

    In order to overload the calculateMomentOfInertia() function, we will add an argument that will never be used; this argument will serve only as a eyewitness to set the difference between both versions of the function. This eyewitness argument can be anything: an integer, a character, a string, a float, etc. For our example, we will make it a simple integer. To use the version applied to the triangle, we will provide this argument to overload the calculateMomentOfInertia() function. When called with only two arguments, the rectangle version will apply.
     
    Change the file as follows:
     
    package momentofinertia1;
    import java.util.Scanner;
    
    public class Main {
        // Rectangle
        static double calculateMomentOfInertia(double b, double h) {
    	return b * h * h * h / 3;
        }
    
        // Semi-Circle
        static double calculateMomentOfInertia(double R) {
    	final double PI = 3.14159;
    	
    	return R * R * R * R * PI/ 8;
        }
    	
        // Triangle
        static double calculateMomentOfInertia(double b, double h, int i) {
    	return b * h * h * h / 12;
        }
        
        static void main(String[] args) {
            Scanner scnr = new Scanner(System.in);
    	double base = 7.74, height = 14.38, radius = 12.42;
    		
    	System.out.println(
    	  "Rectangle - Moment of inertia with regard to the X axis: ");
    	System.out.printf("I = %fmm", 
    		calculateMomentOfInertia(base, height));
    	
            System.out.println("\nSemi-Circle - Moment of inertia of a " +
    			  "semi-circle with regard to the X axis: ");
    	System.out.printf(
    		"I = %fmm", calculateMomentOfInertia(radius));
    		
    	System.out.println("\nEnter the dimensions of the triangle");
    	System.out.print("Base:   ");
    	base = scnr.nextDouble();
    	System.out.print("Height: ");
    	height = scnr.nextDouble();
    
    	System.out.println(
    	 "\nTriangle - Moment of inertia with regard to the X axis: ");
    	System.out.printf("I = %fmm",
    		calculateMomentOfInertia(base, height, 1));
    
    	System.out.println();
        }
    }

  7. Execute the program. Here is an example:
     
    Rectangle - Moment of inertia with regard to the X axis: 
    I = 7671.783954mm
    Semi-Circle - Moment of inertia of a semi-circle with regard to the X axis: 
    I = 9344.281263mm
    Enter the dimensions of the triangle
    Base:   5.52
    Height: 3.84
    
    Triangle - Moment of inertia with regard to the X axis: 
    I = 26.046628mm
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Class Construction

 

Method Initializer

Imagine you are writing a program for a business that sells flowers:

Flower Carnation Lilies Roses Live Plant Orchids
Type Carnation Lilies Roses Live Plants Orchids
Color Red Yellow Red Green White
Arrangement Basket Basket Bouquet Basket Vase
Price 45.95 39.95 85.95 60.95 55.95

Consider the following program:

class Flower {
    int type;
    int color;
    char arrangement;
    double unitPrice;
}

public class Exercise {
    static void main(String[] args) {
	Flower flr = new Flower();

        System.out.println("Flower Type:  " +  flr.type);
        System.out.println("Flower Color: " +  flr.color);
        System.out.println("Arrangement:  " +  flr.arrangement);
        System.out.printf("Price:        %.2f", flr.unitPrice);
    }
}

This would produce:

Flower Type:  0
Flower Color: 0
Arrangement:
Price:        0.00

If you declare a variable of a class in your program, when the program comes up, the compiler reserves enough memory space for each member of the class. The memory space reserved for each member variable is filled with an initial value based on its type. For a String or a char field, the space would be left empty. For an integer type, the space would be filled with 0.

A better way to take care of this is to provide a value whose role would be to initialize the member variables with the values of your choice. A method that initializes an object can return any value but it is preferable to be of type void because its primary purpose is to reset the values. Since this method would give a starting value to all member variables that need to be initialized, it should have an equivalent argument for each of the member variables that it would initialize. Here is an example:

public class Flower {
    int type;
    int color;
    char arrangement;
    double unitPrice;

    void initializer(int tp, int clr, char arng, double price) {
    }
}

The method initializer does not have to initialize all members of the class. For example, the previous execution of the program showed that the member variables that are of type String or char are initialized with an empty string or character. In such a case, you may not have to initialize such variables. To implement a method initializer, simply assign its argument to the corresponding member variable of the class. Here are examples:

public class Flower {
    int type;
    int color;
    char arrangement;
    double unitPrice;

    void initializer(int tp, int clr, char arng, double price) {
        type = tp;
        color = clr;
        arrangement = arng;
        unitPrice = price;
    }
}

You can call a method initializer after declaring the instance of the class to give it initial values. Here is an example:

class Flower {
    int type;
    int color;
    char arrangement;
    double unitPrice;

    void initializer(int tp, int clr, char arng, double price) {
	type = tp;
        color = clr;
        arrangement = arng;
        unitPrice = price;
    }
}

public class Exercise {
    static void main(String[] args) {
	Flower flr = new Flower();
        flr.initializer(3, 7, 'V', 45.95D);

        System.out.println("Flower Type:  " +  flr.type);
        System.out.println("Flower Color: " +  flr.color);
        System.out.println("Arrangement:  " +  flr.arrangement);
        System.out.printf("Price:        %.2f", flr.unitPrice);
    }
}

This would produce:

Flower Type:  3
Flower Color: 7
Arrangement:  V
Price:        $45.95

Using a method initializer, after initializing the object, you can use the values it holds as you see fit.

Practical LearningPractical Learning: Introducing Constructors

  1. Create a new Java Application and name it Geometry3
  2. In the Projects window, under Geometry3, expand Source Packages.
    To create a new class, in the Projects window, under the Geometry3 folder, right-click the Geometry3 sub-folder -> New -> Java Class...
  3. Set the Name to Circle and click Finish

Default Constructor

A constructor is a special method that is created when the object comes to life. This particular method holds the same name as the class and it initializes the object whenever that object is created. When you create a class, if you do not create a constructor, the compiler creates one for you; this is useful because it lets all other objects of the program know that the object exists. This compiler-created constructor is called the default constructor. If you want, you can create your own constructor.

To create a constructor, declare a method that holds the same name as the class. The method must not return any value. Here is an example:

class Flower {

    Flower() {
    }

}

When you declare an instance of the class, whether you use that object or not, a constructor for the object is created. When an instance of a class has been declared, the default constructor is called, whether the object is used or not. This is illustrated in the following program:

class Flower {
    int type;
    int color;
    char arrangement;
    double unitPrice;

    Flower() {
        System.out.println("New Flower Order");
    }
}

public class Exercise {
    static void main(String[] args) {
	Flower flr = new Flower();
    }
}

This would produce:

New Flower Order

As you can see, even though the flr variable was not used, just its declaration was enough to signal it. You might find it sometimes convenient to create your own constructor because, whether you create an empty constructor or not, this does not negatively impact your program.

Practical LearningPractical Learning: Creating a Default Constructor

  1. To create a default constructor, in the Code Editor, right-click somewhere under the name of the class and click Insert Code...
     
    Code Editor
  2. In the menu that appears, click Constructor...
     
    Code Editor
  3. Change the file as follows:
     
    package geometry3;
    
    public class Circle {
        double radius;
    
        public Circle() {
        }
    
        double calculateDiameter() {
            return radius * 2;
        }
    
        double calculateCircumference() {
            return calculateDiameter() * 3.14159;
        }
    	
        double calculateArea() {
            return radius * radius * 3.14159;
        }
    }

The Constructor Initializer

A constructor can be used to initialize the fields of a class. As such, a constructor provides a valuable alternative to a method initializer, the type of method we saw earlier. To use a constructor to initialize the member variables of a class, provide as arguments the necessary variables that you intend to initialize. You don't have to initialize all member variables in the constructor, only those that need to be initialized. In fact, you should initialize only those members that you think the other objects would need when using this object. This means that your object may have fields that, either the external objects don't need to modify (or access) or the member variable(s) will be initialized later when called from the needed object(s).

To implement a default constructor, you can just initialize the desired members of the class. For a member variable of a numeric type, you can just assign the desired constant to each. If the variable is a character, assign a single-quoted symbol to it. If the variable is a string, then assign a double-quoted value to the variable. Here are examples:

class Flower {
    int type;
    int color;
    char arrangement;
    double unitPrice;

    Flower() {
        type        = 1;
        color       = 1;
        arrangement = 'V';
        unitPrice   = 0D;
    }
}

public class Exercise {
    static void main(String[] args) {
	Flower flr = new Flower();

	System.out.println("Flower Type:  " +  flr.type);
        System.out.println("Flower Color: " +  flr.color);
        System.out.println("Arrangement:  " +  flr.arrangement);
        System.out.printf("Price:        %.2f", flr.unitPrice);
    }
}

This would produce:

Flower Type:  1
Flower Color: 1
Arrangement:  V
Price:        0.00

Practical LearningPractical Learning: Creating a Default Constructor

  1. To create a default constructor, change the file as follows:
     
    package geometry3;
    
    public class Circle {
         double radius;
    
        Circle() {
            this.radius = 0.00;
        }
        
        . . . No Change
    }
  2. Access the Main.java file and change it as follows:
     
    package geometry3;
    import java.util.Scanner;
    
    public class Main {
        static void main(String[] args) {
            double rad;
            Circle round = new Circle();
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the radius of the circle: ");
            rad = scnr.nextDouble();
            round.radius = rad;
            
            System.out.println("\nCircle Characteristics");
            System.out.printf("Radius:        %f\n", round.radius);
            System.out.printf("Diameter:      %f\n", round.calculateDiameter());
            System.out.printf("Circumference: %f\n", 
    		round.calculateCircumference());
            System.out.printf("Area:          %f", round.calculateArea());
        }
    }
  3. Execute the application to test it. Enter the radius as 44.86 and press Enter:
     
    Enter the radius of the circle: 44.86
    
    Circle Characteristics
    Radius:        44.860000
    Diameter:      89.720000
    Circumference: 281.863455
    Area:          6322.197291

Constructor Overloading

The default constructor is the favorite place to provide default values to the fields of a class. Besides the default constructor, you can add as many constructors as you judge necessary. This feature allows you to create various constructors for different reasons. This also means that the methods or constructors of a class can be overloaded.

One of the rules of method overloading consists of having methods with different types of arguments. The most basic constructor you would create can use a single argument. When implementing a constructor that takes one argument, you should initialize the member that corresponds to the unique argument and initialize the other members with default values. Here is an example:

class Flower {
    int type;
    int color;
    char arrangement;
    double unitPrice;
 
    Flower(int tp) {
        type        = tp;
        color       = 1;
        arrangement = 'V';
        unitPrice   = 0D;
    }
}

If you create a class with only one constructor as in the current example, when declaring an instance of the class, you must use that constructor: you cannot use the default constructor that does not take an argument. When declaring the variable, initialize it with a constructor with parentheses and provide the value(s) in the parentheses of the constructor. Here is an example:

class Flower {
    String type;
    String color;
    String arrangement;
    double unitPrice;
 
    Flower(String tp) {
        type = tp;
        color = "Red";
        arrangement = "Basket";
        unitPrice = 55.95D;
    }
}

public class Exercise {
    static void main(String[] args) {
	Flower flr = new Flower("Tulips");

	System.out.println("Flower Type:  " +  flr.type);
        System.out.println("Flower Color: " +  flr.color);
        System.out.println("Arrangement:  " +  flr.arrangement);
        System.out.printf("Price:        %.2f", flr.unitPrice);
    }
}

This would produce:

Flower Type:  Tulips
Flower Color: Red
Arrangement:  Basket
Price:        $35.95

In the same way, you can create different constructors for different initializations, although it would not be realistic to create a different constructor for each variable. If you create different constructors with different arguments to initialize (remember the rules of method overloading) the objects, when declaring the classes, make sure you initialize each instance with the right number of arguments; otherwise, the compiler would complain.

If you create a class with only one constructor and that constructor has at least one argument, the default constructor would not be available anymore. If you want to access a default constructor of an object, you have two alternatives:

  • If you do not create any constructor at all on a class, the default constructor would always be available whenever you invoke that class
  • If you create at least one constructor on a class and supply at least one argument to that constructor, you must explicitly create a default constructor for your class

Practical LearningPractical Learning: Overloading a Constructor

  1. Access the Circle.java tab
  2. To create another constructor, in the Code Editor, right-click somewhere inside the class and click Insert Code...
  3. In the menu that appears, click Constructor...
  4. In the Generate Constructor dialog box, click the check box of radius
     
    Generate Constructor
  5. Click Generate
  6. Access the Main.java file and change it as follows:
     
    package geometry3;
    import java.util.Scanner;
    
    public class Main {
        static void main(String[] args) {
            double rad;
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the radius of the circle: ");
            rad = scnr.nextDouble();
            Circle round = new Circle(rad);
            
            System.out.println("\nCircle Characteristics");
            System.out.printf("Radius:        %f\n", round.radius);
            System.out.printf("Diameter:      %f\n", round.calculateDiameter());
            System.out.printf("Circumference: %f\n", 
    		round.calculateCircumference());
            System.out.printf("Area:          %f", round.calculateArea());
        }
    }
  7. Execute the application to test it. Enter the radius as 126.93 and press Enter:
     
    Enter the radius of the circle: 126.93
    
    Circle Characteristics
    Radius:        126.930000
    Diameter:      253.860000
    Circumference: 797.524037
    Area:          50614.863034

Classes Combinations

 

Class Nesting

A class can be created inside of another class. A class created inside of another is referred to as nested. To nest a class, simply create it as you would any other. Here is an example of a class called Inside that is nested in a class called Outside:

public class Outside {
    public class Inside {
    }
}

In the same way, you can nest as many classes as you wish in another class and you can nest as many classes inside of other nested classes if you judge it necessary. Just as you would manage any other class so can you exercise control on a nested class. For example, you can declare all necessary fields, properties, or methods in the nested class or in the nesting class. Here is an example:

public class Outside {
    public class Inside {
	Inside() {
	    System.out.println(" -= Inside =-");
	}
    }

    Outside() {
	System.out.println(" =- Outside -=");
    }
}

A Class as a Field

Just like any of the variables we have used so far, you can make a class a member variable of another class. To use a class in your own class, of course you must have that class. You can use one of the built-in classes of the Java language or you can first create your own class. Here is an example of a class:

class Point {
    int x;
    int y;
}

A field is a member variable created from another class instead of a primitive type. To use one class as a member variable of another class, simply declare its variable as you would proceed with any of the member variables we have declared so far. Here is an example:

class Point {
    int x;
    int y;
}

public class CoordinateSystem {
    Point ptStart;
}

After a class has been declared as a member variable of another class, it can be used regularly. Because the member is a class, declared as a reference, there are some rules you must follow to use it. After declaring the member variable, you must make sure you have allocated memory for it. You must also make sure that the variable is initialized appropriately before it can be used; otherwise you would receive an error when compiling the program.

Returning a Class or Passing a Class

 

Returning a Class From a Method

Like a value from a regular type, you can return a class value from a method of a class. To do this, you can first declare the method and specify the class as the return type. Here is an example:

class Point {
    int x;
    int y;
}

public class CoordinateSystem {
    Point ptStart;
    Point ptEnd;

    Point getThePoint() {
    }
}

After implementing the method, you must return a value that is conform to the class, otherwise you would receive an error when compiling the application. You can proceed by declaring a variable of the class in the body of the method, initializing the variable, and then returning it. Here is an example:

class Point {
    int x;
    int y;
}

public class CoordinateSystem {
     Point ptStart;
     Point ptEnd;

    Point getThePoint() {
	Scanner scnr = new Scanner(System.in);
        Point pt = new Point();

        System.out.print("Enter the x coordinate of the point: ");
        pt.x = scnr.nextShort();
        System.out.print("Enter the y coordinate of the point: ");
        pt.y = scnr.nextShort();
        return pt;
    }
}

Once a method has returned a value of a class, the value can be used as normally as possible.

Practical LearningPractical Learning: Returning a Class From a Method

  1. To create a method that returns a class, change the Main.java file as follows:
     
    package geometry3;
    import java.util.Scanner;
    
    public class Main {
         static Circle create() {
            double r = 0;
            Circle circ = new Circle();
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the radius of the circle: ");
            r = scnr.nextDouble();
            circ.radius = r;
            return circ;
        }
        
        static void main(String[] args) {
            Circle round = create();
            
            System.out.println("\nCircle Characteristics");
            System.out.printf("Radius:        %f\n", round.radius);
            System.out.printf("Diameter:      %f\n", round.calculateDiameter());
            System.out.printf("Circumference: %f\n",
    		round.calculateCircumference());
            System.out.printf("Area:          %f", round.calculateArea());
        }
    }
  2. Execute the application to test it. Enter the radius as 6.12 and press Enter:
     
    Enter the radius of the circle: 6.12
    
    Circle Characteristics
    Radius:        6.120000
    Diameter:      12.240000
    Circumference: 38.453062
    Area:          117.666368

Passing a Class as Argument

Once a class has been created, it can be used like any other variable. For example, its variable can be passed as argument to a method of another class. When a class is passed as argument, its members are available to the method that uses it. Here is an example:

import java.util.Scanner;

class Point {
    int x;
    int y;
}

class CoordinateSystem {
    Point ptStart;
    Point ptEnd;

    Point getThePoint() {
	Scanner scnr = new Scanner(System.in);
        Point pt = new Point();

        System.out.print("Enter the x coordinate of the point: ");
        pt.x = scnr.nextInt();
        System.out.print("Enter the y coordinate of the point: ");
        pt.y = scnr.nextInt();
        return pt;
    }
}

public class Exercise {
     static CoordinateSystem identifyCoordinates() {
        CoordinateSystem coord = new CoordinateSystem();

        System.out.println("Start Point");
        coord.ptStart = coord.getThePoint();

        System.out.println("End Point");
        coord.ptEnd = coord.getThePoint();

        return coord;
    }

     static void show(CoordinateSystem c) {
        System.out.println("Coordinate System");
        System.out.printf("Starting Point: P(%d, %d)", c.ptStart.x, c.ptStart.y);

	System.out.println();

        System.out.printf("Ending Point:   Q(%d, %d)", c.ptEnd.x, c.ptEnd.y);
    }

    static void main(String[] args) {
	CoordinateSystem coord = identifyCoordinates();

        show(coord);
    }
}

Here is an example of running the program:

Start Point
Enter the x coordinate of the point: 1
Enter the y coordinate of the point: 5

End Point
Enter the x coordinate of the point: 2
Enter the y coordinate of the point: 5
Coordinate System
Starting Point: P(1, 5)Ending Point:   Q(2, 5)

As done for the arguments of primitive types, you can pass more than one class as argument to a method. Because classes are always used as references, when passing a class as argument, it is implied to be passed by reference.

Practical LearningPractical Learning: Passing a Class as Argument

  1. To create a method that receives a class as argument, change the Main.java file as follows:
     
    package geometry3;
    import java.util.Scanner;
    
    public class Main {
         static Circle create() {
            double r = 0;
            Circle circ = new Circle();
            Scanner scnr = new Scanner(System.in);
            
            System.out.print("Enter the radius of the circle: ");
            r = scnr.nextDouble();
            circ.radius = r;
            return circ;
        }
        
         static void show(Circle round) {
            System.out.println("\nCircle Characteristics");
            System.out.printf("Radius:        %f\n", round.radius);
            System.out.printf("Diameter:      %f\n", round.calculateDiameter());
            System.out.printf("Circumference: %f\n",
                    round.calculateCircumference());
            System.out.printf("Area:          %f", round.calculateArea());
        }
        
        static void main(String[] args) {
            Circle circular = create();
            show(circular);
        }
    }
  2. Execute the application to test it. Enter the radius as 6.12 and press Enter:
     
    Enter the radius of the circle: 58.08
    
    Circle Characteristics
    Radius:        58.080000
    Diameter:      116.160000
    Circumference: 364.927094
    Area:          10597.482821

Involving a Class and its Own Methods

 

Passing a Class as its Own Argument

An instance of a class can be passed as an argument to one of its own methods (if you have programmed in C++, an example of this implementation is the copy constructor; although you can legitimately create a copy constructor in Java, it does not have the exact same concept as in C++). To do this, you primarily pass the argument as if it were any class. Here is an example:

class Point {
    int x;
    int y;

    void equivalent(Point same) {
    }
}

Then, in the body of the method, do whatever you want. You can, or you may not, use the argument. Still, if you decide to use the argument, know that all of the other members of the class are available through the argument. Probably the simplest way to use the argument is the assign each of of its values to the equivalent member of the class. Here is an example:

class Point {
    int x;
    int y;

    void equivalent(Point same) {
        this.x = same.x;
        this.y = same.y;
    }
}

When calling the method, make sure you pass an instance of the class to it. You can first create and define the class, then pass it. Here is an example:

class Point {
    int x;
    int y;

    void equivalent(Point same) {
        this.x = same.x;
        this.y = same.y;
    }
}

public class Exercise {
    
     static void showPoint(Point pt) {
        System.out.print("Point Coordinates: ");
        System.out.printf("A(%d, %d)", pt.x, pt.y);
    }

    static void main(String[] args) {
	Point pt = new Point();

        pt.x = 4;
        pt.y = 6;
        showPoint(pt);

	System.out.println();

        Point one = new Point();
        one.equivalent(pt);
        showPoint(one);
    }
}

This would produce:

Point Coordinates: A(4, 6)
Point Coordinates: A(4, 6)

Instead of first declaring a variable of the class and initializing it, you can create an instance of the class in the parentheses of the calling method. To do this, you may need a constructor that can specify the values of the fields of the class so the argument can be rightfully initialized. Here is an example:  

class Point {
    int x;
    int y;

    Point() {
    }

    Point(int xCoord, int yCoord) {
        this.x = xCoord;
        this.y = yCoord;
    }

    void equivalent(Point same) {
        this.x = same.x;
        this.y = same.y;
    }
}

public class Exercise {
    
     static void showPoint(Point pt) {
        System.out.print("Point Coordinates: ");
        System.out.printf("A(%d, %d)", pt.x, pt.y);
    }

    static void main(String[] args) {
	Point pt = new Point();

        pt.x = 4;
        pt.y = 6;
        showPoint(pt);

	System.out.println();

        Point one = new Point();
        one.equivalent(new Point(-3, 2));
        showPoint(one);
    }
}

Instead of a formal method, you can use a constructor of the class to pass an instance of the same class. Then, in the constructor, use the argument as you see fit, knowing that all the members of the class are available. Here is an example:

class Point {
    int x;
    int y;

    Point() {
    }

    Point(int xCoord, int yCoord) {
        this.x = xCoord;
        this.y = yCoord;
    }

    Point(Point same) {
        this.x = same.x;
        this.y = same.y;
    }
}

Obviously the purpose of passing a class to one of its own methods is not to find its equivalent. Instead, you can create a method that takes an instance of the same class but modifies that instance. For example, for our Point class, we may want to create a new point that is distanced by one unit from the current Point object. Here is an example of doing that:

class Point {
    int x;
    int y;

    Point() {
    }

    Point(int xCoord, int yCoord) {
        this.x = xCoord;
        this.y = yCoord;
    }

    void equivalent(Point same) {
        this.x = same.x;
        this.y = same.y;
    }

    void createPointOneUnitAway(Point addUnit) {
        this.x = addUnit.x + 1;
        this.y = addUnit.y + 1;
    }
}

public class Exercise {
    
     static void showPoint(Point pt) {
        System.out.print("Point Coordinates: ");
        System.out.printf("A(%d, %d)", pt.x, pt.y);
    }

    static void main(String[] args) {
	Point pt = new Point();

        pt.x = 4;
        pt.y = 6;
        showPoint(pt);
	System.out.println();

        Point one = new Point();
        one.createPointOneUnitAway(pt);
        showPoint(one);
	System.out.println();

        one.createPointOneUnitAway(new Point(-8, -3));
        showPoint(one);
    }
}

This would produce:

Point Coordinates: A(4, 6)
Point Coordinates: A(5, 7)
Point Coordinates: A(-7, -2)

Returning a Class From its Own Method

You can create a method in a class that returns an instance of the class. To start, on the left side of the method, enter the name of the class. Here is an example:

class Point {
    Point MethodName() {
    }
}

There are various ways you can deal with the method. If you want to return a new value of the class, you can declare an instance of the class, initialize it, and then return it. Here is an example:

class Point {
    int x;
    int y;

    Point() {
    }

    Point(int xCoord, int yCoord) {
        this.x = xCoord;
        this.y = yCoord;
    }

    Point(Point same) {
        this.x = same.x;
        this.x = same.x;
    }

    Point advanceBy5() {
        Point some = new Point();
        some.x = 5;
        some.y = 5;
        return some;
    }
}

public class Exercise {
    
     static void showPoint(Point pt) {
        System.out.print("Point Coordinates: ");
        System.out.printf("A(%d, %d)", pt.x, pt.y);
    }

    static void main(String[] args) {
	Point pt = new Point();

        pt.x = 4;
        pt.y = 6;
        showPoint(pt);

        Point away5 = pt.advanceBy5();
        showPoint(away5);
    }
}

This would produce:

Point Coordinates: A(4, 6)
Point Coordinates: A(5, 5)

Alternatively, you can declare an instance of the class, use the current values of the class combined with those of the instance to get new values, and then return the instance. Here is an example:

class Point {
    int x;
    int y;

    Point() {
    }

    Point(int xCoord, int yCoord) {
        this.x = xCoord;
        this.y = yCoord;
    }

    Point(Point same) {
        this.x = same.x;
        this.x = same.x;
    }

    Point advanceBy5() {
        Point some = new Point();
        some.x = this.x + 5;
        some.y = this.y + 5;
        return some;
    }
}

public class Exercise {
    
     static void showPoint(Point pt) {
        System.out.print("Point Coordinates: ");
        System.out.printf("A(%d, %d)", pt.x, pt.y);
    }

    static void main(String[] args) {
	Point pt = new Point();

        pt.x = 4;
        pt.y = 6;
        showPoint(pt);
	System.out.println();

        Point away5 = pt.advanceBy5();
        showPoint(away5);
    }
}

This would produce:

Point Coordinates: A(4, 6)
Point Coordinates: A(9, 11)

Remember that, to call the method, if it is not static, you will need to declare an instance of the class from where you are calling the method. The second type of implementation consists of modifying the instance of the class that is calling the method. For example, you can add values to its fields or you can perform any other operation you want on the members of the calling instance. is an example:

class Point {
    int x;
    int y;

    Point() {
    }

    Point(int xCoord, int yCoord) {
        this.x = xCoord;
        this.y = yCoord;
    }

    Point(Point same) {
        this.x = same.x;
        this.x = same.x;
    }

    // This method adds 1 to each field of the class
    // to get a new point away North-East of the current point
    Point createPointOneUnitAway() {
        this.x = this.x + 1;
        this.y = this.y + 1;

        return this;
    }
}

public class Exercise {
    
     static void showPoint(Point pt) {
        System.out.print("Point Coordinates: ");
        System.out.printf("A(%d, %d)", pt.x, pt.y);
    }

    static void main(String[] args) {
	Point pt = new Point();

        pt.x = 4;
        pt.y = 6;
        showPoint(pt);
	System.out.println();

        Point one = new Point(-8, 5);
        Point another = one.createPointOneUnitAway();
        showPoint(another);
    }
}

This would produce:

Point Coordinates: A(4, 6)
Point Coordinates: A(-7, 6)

As we have learned now, you can create a method that takes an argument that is the same type as its parent class. In the method, you can access any member of the class, including calling the other methods of the class.

 
     

Previous Copyright © 2008-2012, FunctionX Next