aspose file tools*
The moose likes Beginning Java and the fly likes returning a object type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "returning a object type" Watch "returning a object type" New topic
Author

returning a object type

Sri Sanjana
Greenhorn

Joined: Aug 12, 2009
Posts: 6
hello frnds,
I have one more observation
In kathy sierra chapter 2 and section named "Returning a value" it was stated
"In a method with an object reference return type, you can return any
object type that can be implicitly cast to the declared return type".
That is fine.But my point is we can even return any object type that can be explicitly casted to declared return type subjected to the following condition.
class Parent{
public void testMe(){

}
}

class Child extends Parent{
public Child sample(){
Parent parent = new Child();
System.out.println("sample execute");
return (Child)parent;
}
}

public class testMe{
public static void main(String[] args) {
Child child = new Child();
System.out.println("child method executed without exception"+child.sample());
}
}

Regards
Sri
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3829

In kathy sierra chapter 2


Which one ? She has written many books .


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Sri Sanjana
Greenhorn

Joined: Aug 12, 2009
Posts: 6
SCJP Sun Certified
Programmer for Java 5
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3553
    
  15
Sri Sanjana wrote:But my point is we can even return any object type that can be explicitly casted to declared return type subjected to the following condition.


You need to distinguish between object type and reference type. In your example your object type is Child, but your reference type is Parent. As your object type is Child then of course you can return it from a method whose declared return type is Child.


Joanne
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3829

Sri Sanjana wrote:... But my point is we can even return any object type that can be explicitly casted to declared return type subjected to the following condition.


Yes. But the actual object being casted (at runtime) should be of return type or any subtype of it (Child in this case), Or you'll get a ClastCastException.

(Got little late replying, Joanne has already replied )
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: returning a object type