简体   繁体   中英

Java Variables of Interface type

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!

variable.method_2() won't compile as variable is of type foo . foo does not have a method method_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.

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

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).

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM