Java入门第90课——重写Cell类的toString方法

问题

    Object是Java的继承root类,Java类继承了Object的所有方法,如:toString(),hashCode(),equals(),其中toString()方法的特点如下:

    1),toString()方法返回对象的文本描述。

    2),经常被系统默认调用,默认返回:全限定名@HashCode,默认调用时指输出对象时会默认调用toString方法。

    3),建议Java类覆盖toString(),返回合理的文本。

    本案例要求在Cell类中覆盖toString方法,返回行列的值,例如:6,3。

方案

    首先,新建Cell类,然后在其中覆盖toString方法,返回row和col的值;

    然后,测试toString方法是否覆盖生效。首先,在JavaSE工程下的day02包下新建TestCell,然后,在该类中添加测试方法testToString,最后,实例化一个Cell类的对象,其row、col为6、3,并输出该对象。

步骤

    实现此案例需要按照如下步骤进行。

步骤一:新建Cell类

    新建Cell类,然后在其中覆盖toString方法,返回row和col的值,代码如下所示:

    package day02;
    
    public class Cell{
        int row;
        int col;
        
        public Cell(int row,int col){
            this.row=row;
            this.col=col;
        }
        
        public Cell(){
            this(0,0);
        }
        
        public Cell(Cell cell){
            this(cell.row,cell.col);
        }
        
        public void drop(){
            row++;
        }
        
        public void moveRight(){
            col++;
        }
        
        public void moveLeft(){
            col--;
        }
        
        @Override
        public String toString(){
            return row+","+col;
        }
    }

步骤二:写测试方法

    测试toString方法是否覆盖生效。首先,在JavaSE工程下day02包下新建TestCell,然后,在该类中添加测试方法testToString,最后,实例化一个Cell类的对象,其row、col为6、3,并输出该对象,代码如下所示:

    package day02;
    
    import org.junit.Test;
    
    public class TestCell{
     /**
      *测试toString方法
      */
      @Test
      public void testToString(){
          Cell cell=new Cell(6,3);
          System.out.println(cell); //6,3
      }
    }

步骤三:运行

    运行testToString方法,控制台输出结果如下所示:

    6,3

    从运行结果可以看出,已经成功覆盖了toString方法,返回实际row、col的值6、3。

关注公众号,获取学习视频

发布了139 篇原创文章 · 获赞 82 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/houjunkang363/article/details/102560703