0

In interface ONE I have a method A and in interface TWO I have method B. Both the methods are implemented in class Three. Now I assign an instance of Three to ONE, but still can I call method B of SECOND?

Even if this is possbile, is it correct?

3
  • I code example would be helpful here. Commented Feb 15, 2013 at 14:12
  • 3
    Why don't you just test it? Commented Feb 15, 2013 at 14:12
  • 2
    if class 3 is implementing both interfaces, what do you mean by assigning the object to one of them? Commented Feb 15, 2013 at 14:12

3 Answers 3

5

Assuming you have this:

public interface A
{
    public void methodA();
}

public interface B
{
    public void methodB();
}

public class C implements A,B
{
    public void methodA(){...}
    public void methodB(){...}
}

You should be able to do this:

A a = new C();
a.methodA();

but not this:

a.methodB()

On the other hand, you can do this:

B b = new C();
b.methodB();

but not this:

b.methodA();

EDIT:

This is because you define object a as of being an instance of A. Although you are using a concrete class for the initialization (new C()), you are programming to an interface so only the methods defined in that interface will be visible.

Sign up to request clarification or add additional context in comments.

1 Comment

I exactly meant this. My understanding was java compiler looks only type of the object and fetch the method from the method table. So class C has the implementation for both the interface. Then a.methodB() should pass through without any error. Can you explain the reason for this behavior.
0

Also if One extends Two, you will be able to do that. This may not be a solution, but I am only pointing to another way you can do that.

interface Two
{
void a();
}

interface One extends Two 
{
void b();
}

class Three implements One
{
@Override
public void b() {}

@Override
public void a() {}
}

Then you can have

One one = new Three();
one.a();
one.b();

Comments

0

Remember that you're only able to call methods that are available to the assigned class/interface - it doesnt matter what methods the actual object supports, as far as the compiler is concerned it only looks at the assigned reference and what methods it has.

So, in your case if you assign:

Three three = new Three(); // all of the methods in One, Two and Three (if any) can be invoked here
One one = three;    // Only the methods on One can be invoked here
Two two = three;    // Only the methods on Two can be invoked here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.