zoukankan      html  css  js  c++  java
  • toString()方法细节

    toString(),每一个非基本类型的对象都有一个toString()方法,当编译器需要一个Sting,而你只有一个对象时,该方法会自动调用。

    class WaterSource {
        private String s;
        WaterSource(){
            System.out.println("WaterSource()");
            s = "Constructed";
        }
        public String toString(){return s;}
    }
    public class FuYong01{
        private String valve1,valve2,valve3,valve4;
        private WaterSource source = new WaterSource();
        private int i;
        private float f;
        public String toString(){
            return
                    "valve1 = " + valve1 + " " +  
                    "valve2 = " + valve2 + " " + 
                    "valve3 = " + valve3 + " " +
                    "valve4 = " + valve4 + " 
    " +
                    "1 = " + i + " " + "f = " + f + " " +
                    "source = " + source;  //自动调用toSting方法
        }
    public static void main2(String[] args){
        FuYong01 fy = new FuYong01();
        System.out.println(fy);  //就相当于System.out.println(fy.toSting());
        
        }
    }

    运行结果:
    WaterSource()
    valve1 = null valve2 = null valve3 = null valve4 = null
    1 = 0 f = 0.0 source = Constructed

    注意:

    域中为基本类型是能够被初始化为0,但是对象引用会被初始化为null;看上边输出结果的红色null,就是因为引用的对象。

    每一个类中都重写了一个toSting方法;我还以为同一个文件中只能有一个toSring方法了

  • 相关阅读:
    codeforces 1065F Up and Down the Tree
    初探莫比乌斯反演
    IOI2008 island
    miller——rabin判断素数
    NOIP2018游记
    NP是什么意思?
    word2016如何英汉互译
    2.1数字图像化
    Windows程序内部运行机制
    2.2图像灰度直方图
  • 原文地址:https://www.cnblogs.com/sjxbg/p/5492701.html
Copyright © 2011-2022 走看看