编程语言
首页 > 编程语言> > java中’对象’的默认值是什么?

java中’对象’的默认值是什么?

作者:互联网

参见英文答案 > Why does the default Object.toString() include the hashcode?                                    3个
>            Memory address of variables in Java                                    8个
出于蓝色,我遇到了这个:

public class demo {
    void multiply(){
       System.out.println("HELLO WORLD!")
       }
}

public static void main(String args[]){
        demo e=new demo();
        demo e1=new demo();
        System.out.println(e);
        System.out.println(e1);
    }
}

我执行代码时得到的奇怪输出是:

demo@6e1408

demo@e53108

要么

demo@1888759

demo@6e1408

有人可以向我解释发生了什么事吗?
我得到的值,这是一个对象的默认值,还是我错过了什么?

解决方法:

您必须覆盖要打印的类中的toString()方法.

现在它正在打印Object类toString()方法的默认实现.

From Object class Source code

Returns a string representation of the object. In general, the toString method returns a string that “textually represents” this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + ‘@’ + Integer.toHexString(hashCode())

Returns:
a string representation of the object.


    public String  toString() {
         return getClass().getName() + "@" + Integer.toHexString(hashCode());
     }

所以在你的Demo类中使用Ovveride toString()方法获得所需的O / P.

    public class Demo{

    ----

       @Override
       public String toString() {
             //return something 
       }    
}

标签:java,object,default-value
来源: https://codeday.me/bug/20190831/1774229.html