对象JAVA引用对象的变量格式:对象名.变量名引用对象的方法格式:对象名.方法名例1Vector v = new VectorO;v.addElement("hello world");例2int a|l= {1, 2, 3, 4, 5]int size = a.length;例3System.out.printlnO6
6 对象 ◼ 引用对象的变量 ◼ 格式: 对象名.变量名 ◼ 引用对象的方法 ◼ 格式: 对象名.方法名 ◼ 例1 ◼ Vector v = new Vector(); ◼ v.addElement(“hello world”); ◼ 例2 ◼ int a[]= {1, 2, 3, 4, 5}; ◼ int size = a.length; ◼ 例3 ◼ System.out.println();
对象引用对象JAVA通过对象引用对象的成员变量和成员方法class Qangle (int a, h;q1.set(30, 40);Qangle (a = 10; h = 20;) q1.a = 30;Qangle(int x, int y) (a = x; h = y)q1.h = 40;Qangle(Qangler)a = r.widthO;目的相同h = r.height();第一方式更安全、1更面向对象(数据封装void set(int x, inty) ( a=x; h =yi)直接操纵变量7
7 对象引用对象 ◼ 通过对象引用对象的成员变量和成员方法 class Qangle { int a, h; Qangle () {a = 10; h = 20;} Qangle(int x, int y) {a = x; h = y;} Qangle(Qangle r) { a = r.width(); h = r.height(); } void set(int x, int y) { a=x; h =y;} } ▪ q1.set(30, 40); ▪ q1.a = 30; ▪ q1.h = 40; 目的相同 第一方式更安全、 更面向对象(数据封装) 直接操纵变量
TheJava platformallows youtocreateasmanyobjectsasyouwant (limited,of course,bywhatyoursystemcanhandle)andyoudon'thaveto worryabout destroyingthemTheJava runtimeenvironmentdeletesobjectswhen it determines that they are no longer being used.Thisprocessiscalledgarbagecollection垃圾回收(Garbage Collection)垃圾搜集器(Garbage Collector)周期性地释放不再被引用的对象,自动完成手动完成,System.gcO;public static void gcO -- Runs the garbagecollector.8
8 5.2.2 对象的释放 ◼ 将对象从内存中清除 ◼ 内存的管理(枯燥、容易出错) ◼ 垃圾回收(Garbage Collection) ◼ 垃圾搜集器(Garbage Collector) ◼ 周期性地释放不再被引用的对象,自动完成 ◼ 手动完成,System.gc(); ◼ public static void gc() - Runs the garbage collector. The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection
对象的使用JAVA访问对象的私有(private)成员通过定义一个公共方法来实现class Student {private String name;private String id;Student st= newStudent("aloha""001")Student(Strings1, String s2)Stringn=st.getNameO(name=s1;id=s2;})st.setName("csma");n = st.getName();StringgetName)returnname;void setName(String s)(name=s;)1
9 对象的使用 ◼ 访问对象的私有(private)成员 ◼ 通过定义一个公共方法来实现 class Student { private String name; private String id; Student(String s1, String s2) {name = s1; id = s2;} String getName() {return name;} void setName(String s) {name=s;} } Student st = new Student(“aloha”, “001”); String n = st.getName(); . . st.setName(“csma”); n = st.getName(); .
对象作为参数JAVA对象作为方法的参数[访问权限修饰符] 方法返回类型方法名(参数][throws 异常名]方法体;参数:类型变量名,....类型:基本数据类型/复合类型(对象)参数的传递Pass by value10
10 对象作为参数 ◼ 对象作为方法的参数 [访问权限修饰符] 方法返回类型 方法名(参数) [throws 异常名]{ 方法体; } ◼ 参数: 类型 变量名, . . ◼ 类型: 基本数据类型/复合类型(对象) ◼ 参数的传递 ◼ Pass by value