Reputation: 582
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!
Upvotes: 1
Views: 799
Reputation: 272467
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.
Upvotes: 2
Reputation: 167881
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.)
Upvotes: 1
Reputation: 4551
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
Upvotes: 1
Reputation: 198033
No, it is not. If you want access to method_2
, you have to declare the type of variable
to be bar
.
Upvotes: 2
Reputation: 63084
variable.method_2()
won't compile as variable
is of type foo
. foo
does not have a method method_2()
.
Upvotes: 2