5
类、对象、对象内存图、局部变量与成员变量、private修饰符、this、封装笔记
source link: https://segmentfault.com/a/1190000039421433
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
类、对象、对象内存图、局部变量与成员变量、private修饰符、this、封装笔记
发布于 46 分钟前
是对一类具有共同属性和行为的事物的抽象。
1、属性----成员变量(类中方法以外的变量)
2、行为----方法
创建类
创建对象 括号
Phone p = new Phone();
使用成员变量
p.brand
使用方法 括号
p.call()
注意:成员变量有默认值
因为是new出来的,那么就在堆内存中,堆内存中的成员是有默认值的。
对象内存图
P103、P104
多个对象指向相同时
Student s1 = new Student();
Student s2 = s1;
上面这个语句是将s1的地址给了s2,它俩指向同一个列表。
成员变量与局部变量
二者的区别:
1、位置:类内方法外;方法内或方法声明上
2、内存中的位置:堆内存;栈内存
3、生命周期:随对象的消失而消失;随方法的调用结束消失而消失
4、初始化值:有默认初始值;没有默认值,必须先定义、赋初值才能使用
private修饰符
1、是权限修饰符
2、可以修饰成员:成员变量和成员方法
3、private修饰后的成员只能本类访问,保护了本类成员不被别的类访问。
针对private修饰的成员变量
提供方法 get变量名(),来获取变量的值。用public修饰方法
提供方法 set变量名(参数),来设置变量的值。用public修饰方法
public class Student{
private int age;
public int getAge(){
return age;
}
public void setAge(int a){
Age = a;
}
}
public class StudentTest{
public static void main(String[] args){
Student s = new Student();
setAge(5);
System.out.println(s.getAge());
}
this关键字
用来解决局部变量和成员变量同名的情况
上图不用this注释就会变成name = name;
计算机会识别为都是局部变量的name
1、
2、
a对象调用的A类,那么this就代表a对象。
P111
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK