day06--成员变量和局部变量的区别
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package com.inmind.object01;
|
||||
|
||||
public class Demo02 {
|
||||
public static void main(String[] args) {
|
||||
Student s = new Student();
|
||||
//对象的属性值的获取
|
||||
showStudent(s);
|
||||
//对象的属性值的赋值
|
||||
s.name = "张三";
|
||||
s.age = 20;
|
||||
s.id = 1;
|
||||
s.score = 8.8;
|
||||
s.gender = "男";
|
||||
showStudent(s);
|
||||
|
||||
Student s1 = new Student();
|
||||
s1.name = "李四";
|
||||
showStudent(s1);
|
||||
System.out.println("-----------");
|
||||
s.study("java");
|
||||
s1.study("python");
|
||||
}
|
||||
|
||||
//定义一个将指定学生对象的属性全部展示的功能方法
|
||||
public static void showStudent(Student s){
|
||||
System.out.println(s.name);
|
||||
System.out.println(s.age);
|
||||
System.out.println(s.id);
|
||||
System.out.println(s.score);
|
||||
System.out.println(s.gender);
|
||||
}
|
||||
}
|
||||
@@ -7,16 +7,50 @@ package com.inmind.object01;
|
||||
1.在java中描述一类事物,由特征(成员变量)和行为(成员方法,不要使用static描述)组成
|
||||
2.在类中,并不是都必须要主方法,如果一个类要运行,并得到一效果,那么就必须要主方法
|
||||
在java中,一个类只是用来描述一类事物,就不要主方法
|
||||
|
||||
----------------------------------------------------------------------------
|
||||
|
||||
成员变量:处于成员位置的变量
|
||||
成员位置:类中方法外
|
||||
局部变量:在方法中定义的变量
|
||||
|
||||
|
||||
注意:在方法中,如果使用了成员变量与局部变量同名的变量,符合就近原则,直接使用的是局部变量
|
||||
|
||||
成员变量与局部变量的区别:
|
||||
1.定义的位置不同
|
||||
成员变量:类中方法外
|
||||
局部变量:方法中
|
||||
2.作用范围不同
|
||||
成员变量:整个类中都能用
|
||||
局部变量:只能在定义该变量的方法中
|
||||
3.处于内存的位置不同
|
||||
成员变量:在堆内存中
|
||||
局部变量:在栈内存
|
||||
4.默认值不同:
|
||||
成员变量:有默认值的
|
||||
局部变量:没有默认值
|
||||
5.生命周期不同
|
||||
成员变量:随着对象的出现而出现,随着对象的销毁而销毁
|
||||
局部变量:随着方法的出现而出现,随着方法的销毁而销毁
|
||||
|
||||
|
||||
*/
|
||||
public class Student {
|
||||
//属性
|
||||
//属性(成员变量)
|
||||
String name;
|
||||
int age;
|
||||
int id;
|
||||
double score;
|
||||
String gender;
|
||||
|
||||
public void study(String book) {//book就是一个局部变量
|
||||
String name = "呵呵哒";//局部变量
|
||||
//System.out.println(name+"在学"+book);//此处我们希望是展示成员变量name,但是程序采用了局部变量
|
||||
System.out.println(this.name+"在学"+book);
|
||||
}
|
||||
//行为(注意要定义一类事物的行为时,不要加static)
|
||||
|
||||
public void eat(String food) {
|
||||
System.out.println(name+"在吃"+food);
|
||||
}
|
||||
@@ -24,8 +58,4 @@ public class Student {
|
||||
public void sleep() {
|
||||
System.out.println(name+"在睡觉");
|
||||
}
|
||||
|
||||
public void study(String book) {
|
||||
System.out.println(name+"在学"+book);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user