• Post Reply Bookmark Topic Watch Topic
  • New Topic

return statment in method overriding  RSS feed

 
bairava surya
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Base
{

public Base rtc()
{
System.out.println("am in parent");
return new Base();
}
}
class Ret extends Base
{
public Ret rtc()
{
System.out.println("am in child");
return new Ret();

}

public static void main(String[] a)
{
Ret r=new Ret();
Base b=new Base();
Base b1=new Ret();
Ret r1,r2;
Base b2;
b2=b1.rtc();
}
}
output
am in child class but b1.rtc requires b2 to hold the return value y not Ret's object.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
bairava surya wrote:
output
am in child class but b1.rtc requires b2 to hold the return value y not Ret's object.


The Ret instance that is returned IS-A Base type -- so is matching what it is required to return. Remember that subclasses IS-A base class!!

Henry
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Until JavaSE1.4 return types from overriding methods were invariant; they had to be exactly the same type as the overridden method.
In Java5, however, covariant return type was introduced. It is possible to specify a subtype of the overridden method's return type. As Henry says, a subtype IS‑A supertype, and it is here described as a specialisation. Remember a subtype is a more specialised form of its supertype.
Java® Language Specification §8.4.5 wrote:Return types may vary among methods that override each other if the return types are reference types. The notion of return-type-substitutability supports covariant returns, that is, the specialization of the return type to a subtype.
 
bairava surya
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
provide me some program to demonstrate encapsulation?
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
bairava surya wrote:provide me some program to demonstrate encapsulation?

Bairava,

The answer again is: NO. That's not how this site works. We will help you to a solution if you ShowSomeEffort (←click), but we will NOT provide you with ready-made answers.

So, it may just be a language thing, but please stop asking people to do your work for you. There are plenty of other sites around that will do that if you want (although you may have to pay them). Ours doesn't.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!