1:成员变量和局部变量的区别(理解)

      (1)定义位置区别:

           成员变量:定义在类中,方法外。

           局部变量:定义在方法中,或者方法声明上。

      (2)初始化值的区别:

           成员变量:都有默认初始化值。

           局部变量:没有默认初始化值。要想使用,必须先赋值。

      (3)存储位置区别:

           成员变量:存储在堆中。

           局部变量:存储在栈中。

      (4)生命周期区别:

           成员变量:随着对象的创建而存在。随着对象的消失而消失。

           局部变量:随着方法的调用而存在,随着方法调用完毕而消失。更严谨地说当局部变量的作用域结束时,即被销毁。

     (5)就近原则:局部变量有,就用局部变量,局部变量没有,就找成员变量。如果成员变量也没有就报错

     (6)成员变量与局部变量的区别:有所属关系,使用成员变量,否则使用局部变量,详细见下面的例子:

  /*

    成员变量与局部变量的使用区别,有所属关系,使用成员变量,否则使用局部变量

*/

class Demo3

{

    public static void main(String[] args)

    {

       GetSumTool gst = new GetSumTool();

       System.out.println(gst.getSum(2,3));

 

       Rec rec = new Rec();

       rec.height = 10;

       rec.width = 20;

 

       System.out.println("周长为:"+rec.getZhouChang());

       System.out.println("面积为:"+rec.getMianJi());

    }

}

//求两个数的和的工具,第二种好,因为a与b不是这个工具必须有的属性!没有所属关系!

class GetSumTool

{

    //方式一

    //int a;

    //int b;

    //public int getSum(){

    //  return a+b;

    //}

    //方式二

    public int getSum(int a,int b) {

       return a+b;

    }

}

//定义长方形类,求周长与面积

class Rec

{

    //方式一

    int height;

    int width;

    public int getZhouChang(){

       return 2*(height+width);

    }

    public int getMianJi(){

       return height*width;

    }

 

    //方式二

    //public int getZhouChang(int height,int width){

    //  return 2*(height+width);

    //}

    //public int getMianJi(int height,int width){

    //  return height*width;

    //}

}
View Code

相关文章:

  • 2021-07-01
  • 2021-11-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-01
  • 2021-10-15
  • 2022-12-23
猜你喜欢
  • 2021-07-30
  • 2021-11-07
  • 2021-07-12
  • 2021-05-03
  • 2021-12-02
  • 2022-12-23
  • 2021-10-15
相关资源
相似解决方案