开发者

How Object objects return Strings? (Java)

开发者 https://www.devze.com 2023-04-05 15:08 出处:网络
If Obje开发者_高级运维ct is the mother of all classes in the hierarchy, how can he implement a method returning an object of a child class (e.g toString returns a String object)?This is not a problem

If Obje开发者_高级运维ct is the mother of all classes in the hierarchy, how can he implement a method returning an object of a child class (e.g toString returns a String object)?


This is not a problem as long as the child class exists. For example, the following is valid:

A.java:

public class A {
    B b;
}

B.java:

public class B extends A {

}


That's an interesting point: The Object class knows about one of its subclasses, namely String (in particular, to declare and implement the toString() method).

Part of the java language specification is that all classes are implicitly subclasses of Object. Although technically it is "poor design" for a class to refer to one of its subclasses, I think it's an "edge case" and not something to be worried about.


because there is a default implementation of toString on Object that makes sure a String instance is returned. Since every class is an instance of an Object you always get that default implementation for free, although you can and should implement toString on subclasses.

There is nothing preventing methods in any class returning instances of another class. You can always do

return new SomethingElse()

where SomethingElse is another class.

0

精彩评论

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