Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Practice exam 1 K&B q 58

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Hose<E extends Hose>
{
E innerE;

public E get(E e,Hose<E>e2)
{
return e.getE(); //compiler says found Hose
}

E getE()
{
return innerE;
}
}

I know for compiler get() methods return type can only be E nothing else

Please explain clearly ,
 
Zhenyi Luo
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mahtab Alam wrote:public class Hose<E extends Hose>
{
E innerE;

public E get(E e,Hose<E>e2)
{
return e.getE(); //compiler says found Hose
}

E getE()
{
return innerE;
}
}

I know for compiler get() methods return type can only be E nothing else

Please explain clearly ,


I guess it's because when get(E e,Hose<E>e2) is called, e must be instantialized as a specific object corresponding to specific class.
If we want to return E, we have to add a cast. (change return e.getE() to return (E) e.getE() )
On the other hand, if e is not involved, it always works. (Change return e.getE() to return getE() )
 
Joe Allen
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
E e is an element, while Hose<E> e2 is a Host class of E with a method getE() that returns E. That is my take.
 
Himai Minh
Ranch Hand
Posts: 1229
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The trick is what innerE is when Hose is used as a raw type. Hose h = new Hose() is different than Hose<Hose> e = new Hose<Hose>();

Look at this example:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic