This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

returning a object type  RSS feed

 
Sri Sanjana
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Saloon Keeper
Posts: 3998
42
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In kathy sierra chapter 2


Which one ? She has written many books .
 
Sri Sanjana
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
SCJP Sun Certified
Programmer for Java 5
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Vijitha Kumara
Saloon Keeper
Posts: 3998
42
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 )
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!