方法练习4-6~4-8

4-6通过类名调用方法

class Computer{

   double x,y;

   static double max(double a,double b){

       return a>b?a:b;

   }

}

class Example4_6{

   public static void main(String args[]){

      double max=Computer.max(12,45);

  System.out.println(max);

  }

}

4-7向一个方法的基本数据类型参数传值

class Tom

{  void f(int x,double y){

      x=x+1;

  y=y+1;

  System.out.printf("参数xy的值分别是:%d,%3.2f\n",x,y);

  }

}

public class Example4_7

{  public static void main(String args[]){

       int x=10;

   double y=12.58;

   Tom cat=new Tom();

   cat.f(x,y);

   System.out.printf("main方法中xy的值仍然分别是:%d,%3.2f\n",x,y);

   }

}

4-8Tom类中的方法f的参数mouse是jerry类声明的对象,属于引用类型参数

class Jerry{

    int leg;

    Jerry(int n){

       leg=n;

    }

    void setLeg(int n){

       leg=n;

    }

    int getLeg(){

       return leg;

    }

}

class Tom{

    void f(Jerry mouse){

        mouse.setLeg(12); 

        System.out.println("在执行方法f,参数mouse修改了自己的leg的值");

        System.out.println("当前参数mouse的成员leg的值:"+mouse.getLeg());

        mouse=null;        //mouse不在拥有实体

        //mouse.setLeg(12);  //将发生NullPointerExcetion异常

    } 

}

public class Example4_8{

    public static void main(String args[]){

        Tom cat=new Tom();

        Jerry jerry=new Jerry(2);

        System.out.println("在调用方法f之前,jerry的成员leg的值:"+jerry.getLeg());

        cat.f(jerry);

        System.out.println("在调用方法f之后,jerry的成员leg的值:"+jerry.getLeg());

    }

}

posted on 2013-03-24 17:13  jixiuyan  阅读(109)  评论(0编辑  收藏  举报