1

I know that object which is assigned to the reference variable whose type is an interface could be an instance of a class that implements the interface. But for the following code blocks:

public interface foo {
    public abstract void method_1();
}

class bar implements foo {  
    @Overide
    public void method_1() { //Implementation... }

    public void method_2() { //Do some thing... } 
}
.....

foo variable = new bar();
variable.method_1(); // OK;
variable.method_2(); // Is it legal?

Is it possible to make the variable (whose declared type is foo but actual type is bar) call the method_2 which is not declared in the interface ? Thanks in advance!

5 Answers 5

2

Yes, you can cast:

((bar)variable).method_2();

But you probably shouldn't. The whole point of an interface is to only use the methods it provides. If they're not sufficient, then don't use the interface.

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

Comments

2

variable.method_2() won't compile as variable is of type foo. foo does not have a method method_2().

Comments

2

No, it is not. If you want access to method_2, you have to declare the type of variable to be bar.

Comments

1

Is it possible to make the variable (whose declared type is foo but actual type is bar) call the method_2 which is not declared in the interface ?

Not its not possible. It will be a compile time error.

There is other standard deviation also in your code

  1. Interface and class names should be in upper camel case (this is UpperCamelCase).

Comments

1

No, it is not legal. However, you can inspect the type at runtime and cast to the correct type:

if (variable instanceof bar) ((bar)variable).method_2();

(Strictly speaking you can cast without the instanceof check if you know for sure the type is correct, or are happy to get an exception thrown if you are wrong.)

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.