1.什么是类?什么是对象?
1)现实世界是由很多很多对象组成的基于对象抽出了类。
2)对象:真实存在的单个的个体
类:类型/类别,代表一类个体
3)类中可以包含:
3.1)所有对象所共有的属性/特征-----------变量
3.2)所有对象所共有的行为----------------方法
4)一个类可以创建多个对象
同一类型的对象,结构相同,数据不同
5)类是对象的模板,对象是类的具体的实例
2.如何创建类?如何创建对象?如何访问成员?
1)指向同一个对象
2)对一个引用的修改,影响另外一个引用
eg: 房子钥匙基本类型之间画等号:
1)赋值
2)对一个变量的修改,不会影响另外一个变量
eg: 身份证复印件
4.null:空,没有指向任何对象
若引用的值为null,则该引用不能再进行任何操作了
若操作则NullPointerException空指针异常
package oo.day01; //格子类 public class Cell { int row; //行号 int col; //列号 void drop(){ //下落1格 row++; } void moveLeft(int n){ //左移n格 col-=n; } String getCellInfo(){ //获取行号和列号 return row+","+col; } }
package oo.day01; //格子类的测试类 public class CellTest { public static void main(String[] args) { /* Cell c = new Cell();.. . c.row = 2; c.col = 5; c.drop(); c.moveLeft(3); String str = c.getCellInfo(); System.out.println(str); //3,2 */ Cell c = new Cell(); c.row = 2; c.col = 5; printWall(c); //Cell cc=c; c.drop(); //c.row=3 System.out.println("下落后:"); printWall(c); } //打墙+打格 public static void printWall(Cell cc){ for(int i=0;i<20;i++){ //行 for(int j=0;j<10;j++){ //列 if(i==cc.row && j==cc.col){ //行列匹配 System.out.print("* "); }else{ System.out.print("- "); } } System.out.println(); //换行 } } }
package oo.day01; //引用类型画等号与null的演示 public class RefNullDemo { public static void main(String[] args) { Cell c = new Cell(); c.row = 2; c.col = 5; Cell cc = c; //指向了同一个对象 cc.row = 8; System.out.println(c.row); //8 int a=5; int b=a; //赋值 b = 8; System.out.println(a); //5 Cell c1 = new Cell(); c1.row = 2; c1.col = 5; c1 = null; //空,没有指向任何对象 //c1.row = 4; //NullPointerException空指针异常 } }