Rotemk55
Rotemk55

Reputation: 43

How to Access method from a sub- abstract class

I have the following hirarchy:

Interface s
Abstractclass1 implements s
Abstractclass2 extends Abstractclass1 

in Abstractclass2 there is a method unrecognized in s/Abstractclass1 : method2 there is a test code that generate a new s object, i want to use method2 on this object how do i access it?

Upvotes: 1

Views: 57

Answers (2)

user1697575
user1697575

Reputation: 2848

You have to typecast your instance of "S" to Abstractclass2.

e.g.

void myMethod(S myparam)
{
  if (myparam instanceof Abstractclass2)
  {
    ((Abstractclass2)myparam).method2();
  }
} 

Upvotes: 0

aioobe
aioobe

Reputation: 420921

You're not suppose to be able to call method2 on an object with static type Abstractclass1 (or s).

You can't call bark() if you have an Animal (who knows, it might be a Cat in runtime)

So, what to do? Either you change the static type to Abstractclass2 or you do a downcast, as such: ((Abstractclass2) yourObject).method2.

Upvotes: 4

Related Questions