Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem regarding interface reference variable

Tags:

java

interface

I've studied that in case of instance methods, at run time the jvm uses the actual class of instance and in case of class methods the compiler will only look at the declared type of a reference variable not the actual class..

I studied this concept instance method hiding..

And in my proram I've used interface reference variable to store the object of the class and try to access the instance method of the class using this but it raise an error.. My program is as follows:

interface A
{
   void show();
}
class B implements A
 {
   public void show()
   {
      System.out.println("Interface Method");
   }
    void info()
  {
     System.out.println("IN Info");
  }
}
class interDemo
{
   public static void main(String args[])
  {
     A a;
     B b=new B();
      a=b;
      a.show();
      a.info();
  }
}

Please help me to understand the conept...

like image 300
Laawanya Avatar asked Jan 20 '23 19:01

Laawanya


2 Answers

The compiler is telling you that the type A does not have a method called info defined. This is true: the compiler doesn't know that at runtime, the type of a will actually be B, which does have the info method. It would be unsafe to allow the a.info() call to actually be compiled and emitted into bytecodes, there's nothing to say that a will always be of type B.

This is known as static typing. In Java and other static-typed languages, you need to "cast" a variable in order to force the compiler to treat it as another type. In this case, you can write ((B) a).info().

like image 191
sjr Avatar answered Jan 26 '23 00:01

sjr


sjr is correct. Here's another way to look at it:

You're specifying that a A can only show. That means when you have a A reference variable, that's all you can do.

That means any class that is willing to show can implement that interface. Clients that need an object to show can use an A without knowing or caring whether that the underlying class has other methods. This is a key aspect of the abstraction provided by object-oriented programming.

like image 33
Matthew Flaschen Avatar answered Jan 25 '23 23:01

Matthew Flaschen