Wednesday, April 27, 2016

Methods


Today I learned about methods. A method is used to set a behavior for a class. For example with the class person you can create a method to make an object say their name. When writing a method you type (void method_name();{}), with the method_name in lower case. Between the curly brackets you can write code for your method.

After you make your method you can call it in your main class. Since the method has access to the class, you can use the instance variables declared in the class. We can call a method by typing ( name_object.method_name();). Calling a method will run the code in your method.

Below is an example of a method used to calculate the derivative of a function at the point (2,2). First I imported the Math class so I could use it later in my code. Then I made a class called Function with a method productRule. After I created an object called variable, and add data to it. Last I called the method.


import java.lang.Math;

class Function {

     

      int x;

      int y;

      int n;

      int r;

      double derivative;

     

      void productRule(){

            int newn = n-1;

            int newr=r-1;

            derivative = n*Math.pow(x, newn)*Math.pow(y, r)+Math.pow(x,n)*r*Math.pow(y, newr);

            System.out.println("The derivative is: " + derivative);

      }

}



public class Application {

     

      public static void main(String[] args){

            Function variable = new Function();

             variable.x = 2;

             variable.y = 2;

             variable.n = 3;

             variable.r = 3;

             

             variable.productRule();

             

           

           

      }

     

}
     

No comments:

Post a Comment