《JAVA语言程序设计》第3章2.pptVIP

  • 3
  • 0
  • 约8.52千字
  • 约 26页
  • 2017-07-04 发布于四川
  • 举报
* 对象和类(续) 对象的创建 对象的使用 对象的释放 对象的访问 * 对象的创建 对象成员(变量和方法) 静态(static)成员: 属于类 实例成员: 属于对象 创建对象/实例化对象—new 例1: Apple a = new Apple(); (创建对象) 例2: Apple a; (对象的说明) a = new Apple(); (实例化对象) 对象的实例化通过构造方法(constructor)来实现 构造方法的名字与类名相同 构造方法没有返回值 构造方法可以有多个,构成方法的重载(overload) * 例: 对象的实例化和初始化 public static void main(String args[]) { Square s1 = new Square(); Square s2 = new Square(20, 50); Square s3 = new Square(s1); System.out.println(s1.width() +“ ” +s1.height()); System.out.println(s2.width() +“ ” +s2.height()); System.out.println(s3.width() +“ ” +s3.height()); } } class Square { int a, h; Square() { a = 10; h = 20; } Square(int x, int y) { a = x; h = y; } Square(Square s) { a = s.width(); h = s.height(); } int width() { return a;} int height() {return h;} 计算结果: 10 20 20 50 10 20 对象的创建 * 默认构造方法 例 class Apple { int color; } Apple a = new Apple(); 对象实例的判断: null 例 Apple a; if (a == null) System.out.println(“Day dream”); 对象的创建 运行时系统自动赋予 一个空构造函数 如 public Apple() { ; } * 再谈构造方法 对象的创建 class MyTest { MyTest (boolean b) { } public static void main (String args[]) { //MyTest m1 = new MyTest(); MyTest m2 = new MyTest(false); } } class MyTest { MyTest (boolean b) { } MyTest () {} public static void main (String args[]) { MyTest m1 = new MyTest(); MyTest m2 = new MyTest(false); } } 运行时系统自动赋予一个空构造方法, 仅仅当该类没定义构造方法的情况下 * 对象和类(续) 对象的创建 对象的使用 对象的释放 对象的访问 * 对象的使用 通过对象引用对象的成员变量和成员方法 class Square { int a, h; Square () { a = 10; h = 20;} Square(int x, int y) { a = x; h = y; } Square(Square r) { a = r.width(); h = r.height(); } int width() { return a;} int height() {return h;} void set(int x, int y) { a=x; h =y; } } q1.set(30, 40); q1.a = 30; q1.h = 40; 目的相同 第一方式更安全、 更面向对象(数据封装) 避免直接操纵变量 * 对象的使用 引用对象的变量 格式: 对象名.变量名 引用对象的方法 格式: 对象名.方法名 例1 Vector v = new Vector(); v.addElement(“s1”); 例2 int a[]= {1, 2, 3, 4, 5}; int s

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档