对象和类
- 现实世界是有很多对象组成的,基于对象抽出类
- 对象—真实存在的单个个体,类—–代表一类个体
- 类中可以包含成员变量和方法
*所有对象所共有的特征/属性—数据(成员变量)
*所有对象所共有的行为——–方法 - 一个类可以创建多个对象
同一个类创建的对象结构相同,数据不同 - 类是对象的末班,对象是类的具体实例
- 基本类型之间画等号—赋值
*对其中一个变量的修改不影响另一个变量
引用类型之间画等号—指向同一个对象
*对其中一个引用的修改,也会影响另一个引用 - null和NullPointerException(空指针异常)
- null:空,没有指向任何对象,若引用的值为null,则该引用不能做任何操作,否则会出现空指针异常
## 案例 ##
创建一个Cell类
//创建一个格子类
public class Cell {
int row;
int col;
void drop(){ //下落一行
row++;
}
void moveLeft(){ //左移一列
col--;
}
void moveRight(){ //右移一列
col++;
}
String coord(){ //打印格子坐标
return row+","+col;
}
}
创建一个Cell测试
import java.util.Scanner;
public class CellTest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Cell c=new Cell();
c.row=2;
c.col=3;
System.out.println("格子初始坐标:"+c.coord());
do{
System.out.println("请输入操作(1.下落一行,2.左移一行,3.右移一行,0.退出):");
int a=sc.nextInt();
if(a==0){
System.out.println("游戏结束!");
break;
}else {
switch(a){
case 1:c.drop();
print(c);
System.out.println("格子新坐标:"+c.coord());
break;
case 2:c.moveLeft();
print(c);
System.out.println("格子新坐标:"+c.coord());
break;
case 3:c.moveRight();
print(c);
System.out.println("格子新坐标:"+c.coord());
break;
default:System.out.println("输入错误!");
}
}
}while(true);
}
//打印场地及格子位置的方法
public static void print(Cell c){
for(int i=0;i<20;i++){
for(int j=0;j<10;j++){
if(i==c.row&&j==c.col){
System.out.print("* ");
}else{
System.out.print("- ");
}
}
System.out.println();
}
}
}