开发者

How the Inheritance is implemented here?

This is a simple Java code:

public class JTest {
    public static void main(String []args) {
        Integer a = new Intege开发者_JAVA百科r(2);
        Object b = a;
        System.out.print("r = " + b);
    }
}

All objects have a parent Object in Java. When you run this program you will get: r = 2 Why? If I do the same thing with this code:

public class JTest {
    public static void main(String []args) {
        A a = new A();

        Object b = a;
        System.out.print("r = " + b);
    }
}

Where the class A is:

public class A {
    int a;
}

The output will be: r = test.A@9304b1


Integer.toString() returns a string containing the integer's value.

Your class doesn't implement its own toString(), so it uses the default Object.toString() implementation which returns a combination of the object's class and its hash code.


it will invoke toString() method of object on which method called on. if its not implemented Object class provides one by default.

Try overriding it by this way and check the output

public class A {
    int a;
    @Override 
    public Sring toString(){
         return "A has property a = "+this.a;
    }
}


In the first instance, b contains an instance of Integer, so the toString() implementation of Integer is called in the print.

In the second case b contains an instance of A, so the toString() implementation of A is called. Presumably A does not override toString(), so you get the default implementation from Object (package.Class@hash).

EDIT (Since the question changed):

The class A only contains an int field, it does not extend int. If you change A to override toString (you can't extend primitive types like int), you can get what you want:

class A {
    Integer a;

    public A(int i) {
        a = i;
    }

    @Override
    public String toString() {
        return a.toString();
    }
}


When you do System.out.print("r = " + b); Java will invoke b.toString(). The method toString is inherited from Object. In the first case the class Integer overrides toString to return the integer value. Your A class doesn't ovverride toString() and so you get only a default value (object class and hash code)


As an aside, if you want to get the java.lang.Object style output for a type that has overridden toString(), you can use code like this:

public static String toString(Object o) {
  if (o == null) return null;
  return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o));
}


In the first instance Object has a toString method so the actual value would be printed. However, without a toString method like your second implementation, you get sorta like an ID of class/object


In your first case, the Integer class has a 'toString' method that when compbined with "r " + b will give you a text representation of 'a' which will be 2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜