• Post Reply Bookmark Topic Watch Topic
  • New Topic

Accessing a Method which is in all subclasses but not in SuperClass  RSS feed

 
Tej Kumar Ch
Greenhorn
Posts: 15
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a situation which is challenging for me.

Need your suggestions

Is it possible to acces method2 of Subclass1 or SubClass2 from Test Class?

Regards
Tej
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. The type parameter T of your testMethod() method might be SuperClass, which doesn't have the method2() method.

But there's a way to make SuperClass have a method2() method without providing an implementation for that method. Do you know what it is?
 
Tej Kumar Ch
Greenhorn
Posts: 15
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi Paul,

Yes I know that for <T extends SuperClass> T includes super class also.
Paul Clapham wrote:

But there's a way to make SuperClass have a method2() method without providing an implementation for that method. Do you know what it is?

Are you talking about making the SuperClass abstract ?

The problem here is we can't edit the SUperClass, its a thirdParty code.

Regards
Tej
 
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
Tej Kumar Ch wrote:
The problem here is we can't edit the SUperClass, its a thirdParty code.


Without being able to change the superclass, then you are kinda limited on what can be done easily, I guess ...

Tej Kumar Ch wrote:
Is it possible to acces method2 of Subclass1 or SubClass2 from Test Class?


you can ... simply cast the instance to the subclass and call the method2() method, which leads to the next question. Which subclass do you cast it to? Unfortunately, you would be responsible for this. This means that you have to confirm the subclass type before you cast it. If there are lots of subclasses, then this check can get tedious.

Or alternatively, you can make make all the subclasses implement a common interface that has the method2() method. This can be used to check the instanceof, to be cast, and ultimately call the method2() method.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!