成员变量和局部变量的区别
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
开发工具与关键技术:Eclipse
作者:邓莹露
撰写时间:2021年6月17号
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
成员变量和局部变量的区别?
1:在类中的位置不同
成员变量:在类中方法外
局部变量:在方法定义中或者方法声明上
2:在内存中的位置不同
成员变量:在堆内存
局部变量:在栈内存
3:生命周期不同
成员变量:随着对象的创建而存在,随着对象的消失而消失
局部变量:随着方法的调用而存在,随着方法的调用完毕而消失
4:初始化值不同
成员变量:有默认初始化值
局部变量:没有默认初始化值,必须定义,赋值,然后才能使用。 注意事项:
局部变量名称可以和成员变量名称一样,在方法中使用的时候,采用的是就近原则。
例如:
class Text {
//成员变量
//int num = 10;
int num; //0
public void show() {
//int num2 = 20; //局部变量
//可能尚未初始化变量num2
//int num2; //没有默认值
int num2 = 20;
System.out.println(num2);
//int num = 100;
System.out.println(num);
}
}
class Text Demo {
public static void main(String[] args) {
Text v = new Text ();
System.out.println(v.num); //访问成员变量
v.show();
}
}
形式参数是类名的问题
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
开发工具与关键技术:Eclipse
作者:露
撰写时间:2021年6月17号
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
形参参数的问题:
基本类型:形式参数的改变不影响实际参数
引用类型:形式参数的改变直接影响实际参数
形式参数是基本类型
class Demo {
public int sum(int a,int b) {
return a + b;
}
}
//形式参数是引用类型
class Student {
public void show() {
System.out.println("我爱学习");
}
}
class StudentDemo {
//如果你看到了一个方法的形式参数是一个类类型(引用类型),这里其实需要的是该类的对象。
public void method(Student s) { //调用的时候,把main方法中的s的地址传递到了这里 Student s = new Student();
s.show();
}
}
匿名对象
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
开发工具与关键技术:Eclipse
作者:露
撰写时间:2021年6月17号
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
匿名对象:就是没有名字的对象。
匿名对象的应用场景:
1:调用方法,仅仅只调用一次的时候。
2:注意:调用多次的时候,不适合。
3:那么,这种匿名调用有什么好处吗?
有,匿名对象调用完毕就是垃圾。可以被垃圾回收器回收。
4:匿名对象可以作为实际参数传递
class Student {
public void show() {
System.out.println("我爱学习");
}
}
class StudentDemo {
public void method(Student s) {
s.show();
}
}
class NoNameDemo {
public static void main(String[] args) {
//带名字的调用
Student s = new Student();
s.show();
s.show();
System.out.println("--------------");
//匿名对象
//new Student();
//匿名对象调用方法
new Student().show();
new Student().show(); //这里其实是重新创建了一个新的对象
System.out.println("--------------");
//匿名对象作为实际参数传递
StudentDemo sd = new StudentDemo();
//Student ss = new Student();
//sd.method(ss); //这里的s是一个实际参数
//匿名对象
sd.method(new Student());
//再来一个
new StudentDemo().method(new Student());
}
}