版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
格子类
package oo.day03;
//格子类
public class Cell {
int row;//行号
int col;//列号
Cell(){
this(0);
}
Cell(int n){
this(n, n);
}
Cell(int row,int col){
this.row=row;
this.col=col;
}
void drop(){//下落一格
row++;//行号增一
}
void moveleft(int n) {//左移n格
col-=n;//列号减一
}
String getCellInfo() {//获取行号和列号
return row+","+col;//返回行列号
}
void drop(int n) {
row+=n;
}
void moveLeft() {
col--;
}
}
父类
package oo.day03;
//父类
public class Tetromino {
//定义成员变量cells
Cell[] cells;
//成员变量赋初值
Tetromino(){
cells = new Cell[4];
}
void drop(){ //下落
for(int i=0;i<cells.length;i++){
cells[i].row++;
}
}
void moveLeft(){ //左移
for(int i=0;i<cells.length;i++){
cells[i].col--;
}
}
void moveRight(){ //右移
for(int i=0;i<cells.length;i++){
cells[i].col++;
}
}
void print(){ //打印每个格子的坐标
for(int i=0;i<cells.length;i++){
String str = cells[i].getCellInfo();
System.out.println(str);
}
}
}
J型类
package oo.day03;
//J型
public class J extends Tetromino{
J(){
this(0,0);
}
J(int row,int col){
cells[0] = new Cell(row,col);
cells[1] = new Cell(row,col+1);
cells[2] = new Cell(row,col+2);
cells[3] = new Cell(row+1,col+2);
}
}
T型类
package oo.day03;
//T型
public class T extends Tetromino{
T(){
this(0,0);
}
T(int row,int col){
super();//调用父类的无参构造方法---不写则默认
cells[0] = new Cell(row,col);
cells[1] = new Cell(row,col+1);
cells[2] = new Cell(row,col+2);
cells[3] = new Cell(row+1,col+1);
}
}
测试类
package oo.day03;
//T型、J型测试类
public class TJtest {
public static void main(String[] args) {
Tetromino t=new T(2,5);
printWall(t);//先造型后传值
J o2=new J(1,7);
printWall(o2);//Tetromino t=o2 传值的同时造型
}
/*//效力高但是扩展性差
* public static void printWall(T t) {
Cell[] cells=t.cells;
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 10; j++) {
if (i==cells[0].row && j==cells[0].col
||
i==cells[1].row && j==cells[1].col
||
i==cells[2].row && j==cells[2].col
||
i==cells[3].row && j==cells[3].col){
System.out.print("* ");
} else {
System.out.print("- ");
}
}
System.out.println();
}
}
*/
public static void printWall(Tetromino t) {
Cell[] cells=t.cells;
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 10; j++) {
boolean flag=false;//1.假设打-
for (int k = 0; k < cells.length; k++) {
if (i==cells[k].row&&j==cells[k].col) {
flag=true;//2.改为打*
break;
}
}
if (flag) {//3.判断得到结果
System.out.print("* ");
} else {
System.out.print("- ");
}
}
System.out.println();
}
}
}
super调用父类构造演示(与上面代码无关)
package oo.day03;
//super调用父类构造演示
public class SuperDemo {
public static void main(String[] args) {
Boo b = new Boo();
}
}
class Aoo{
Aoo(){
System.out.println("父类构造");
}
}
class Boo extends Aoo{
Boo(){
//super(); //默认调用父类无参构造
System.out.println("子类构造");
//super(); //错误,只能位于子类构造的第1句
}
}