[关闭]
@Hubertoo 2017-07-17T05:26:39.000000Z 字数 2928 阅读 878

OOP.Unit03

达内



知识体系

对象内存管理

对象内存管理

堆内存

栈内存

方法区

继承

extends关键字

继承中的构造方法

方法的重写

  1. class foo{
  2. public void f(){
  3. sysout("haha");
  4. }
  5. }
  6. class hoo extends foo{
  7. public void f(){
  8. sysout("hehe");
  9. }
  10. }
  11. //输出结果是hehe
  12. class foo{
  13. public void f(){
  14. sysout("haha");
  15. }
  16. }
  17. class hoo extends foo{
  18. public void f(){
  19. super.f();
  20. sysout("hehe");
  21. }
  22. }
  23. //输出结果是haha hehe

经典案例

构建Tetromino类,重构T类和J类并测试

  1. package day02;
  2. public class Tetromino {
  3. Cell[] cells;
  4. public Tetromino(){
  5. cells = new Cell[4];
  6. }
  7. //打印格子中四个格子所在的坐标
  8. public void printTetromino(){
  9. String str = "";
  10. for(int i=0; i<cells.length-1; i++){
  11. str += "(" + cells[i].getCellInfo() + "),";
  12. }
  13. str +="(" +cells[cells.length-1].getCellInfo() + ")";
  14. System.out.println(str);
  15. }
  16. //方块的下落一个格子
  17. public void drop(){
  18. for(int i=0; i<cells.length;i++){
  19. cells[i].row++;
  20. }
  21. }
  22. //方块左移一个格子
  23. public void moveLeft(){
  24. for(int i=0; i<cells.length;i++){
  25. cells[i].col--;
  26. }
  27. }
  28. //方块右移一个格子
  29. public void moveRight(){
  30. for(int i=0; i<cells.length;i++){
  31. cells[i].col++;
  32. }
  33. }
  34. }
  35. ---
  36. package day02;
  37. public class TetrominoJ extends Tetromino{
  38. public TetrominoJ(int row, int col){
  39. super();
  40. cells[0] = new Cell(row, col);
  41. cells[1] = new Cell(row, col+1);
  42. cells[2] = new Cell(row, col+2);
  43. cells[3] = new Cell(row+1, col+2);
  44. }
  45. }
  46. ---
  47. package day02;
  48. public class TestTetrominoJ {
  49. public static void main(String[] args) {
  50. Tetromino j = new TetrominoJ(1, 2);
  51. System.out.println("-------打印J坐标 -----");
  52. j.printTetromino();
  53. }
  54. }

重写T类的print方法并测试

  1. //重写Tetromino的print方法并测试
  2. public void print(){
  3. System.out.println("I am a J");
  4. super.print();
  5. }
  6. //测试结果是:I am a J + print出来的坐标

课后作业

  1. class Base{
  2. double size;
  3. String name;
  4. public Base(double size, String name){
  5. this.size = size;
  6. this.name = name;
  7. }
  8. }
  9. public class Sub extends Base{
  10. String color;
  11. public Sub(double size, String name, String color){
  12. super(size,name);
  13. this.color = color;
  14. }
  15. public static void main(String[] args){
  16. Sub s = new Sub(5.6, "测试对象","红色");
  17. System.out.println(s.size + "--" + s.name + "--" + s.color + "--");
  18. }
  19. }
  20. 结果是:5.6--测试对象--红色--
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注