"We cannot create an object of interface but we can create a
variable of it". Discuss the statement with the help of an
example.
(Plz help us to provide immediately.)
Answer Posted / nick
In layman terms it can be said that a interface basicaly
provides a template. Since it does not have any concreet
functions we cannot create its object, as during
implemetation(runtime) there would be no definition found
for the particular function that would have been hardcoded
into the program. Where as using it as a refernce variable
is possible because of the technique provided by java
i.e. 'Virtual Method Invocation'. This enables us to create
a variable of a interface, but at runtime the function
defenition that would be called would be the one of the
object of the class actually being referred. It would get
clear from the following example:
interface Color
{
void green();
void red();
void blue();
}
here if we create a object of interface Color like
Color clr= new Color();
clr.green();
then it would give an error as there is no implementation
available for the function green();
whereas this senario is valid where we have another class
class Implemeter
{
public void green()
{
System.out.println("You selected green color");
}
public void red()
{
System.out.println("You selected red color");
}
}
and now we use like this
Color clr = new Implementer();
clr.green();
then this is absolutely valid as on runtime the function
definition of green() from class Implementer would be
called and not of interface Color. This technique is called
virtual method invocation.
Just let me know if this information was helpful, or if you
have any other doubts.
| Is This Answer Correct ? | 29 Yes | 4 No |
Post New Answer View All Answers
What is the do while loop syntax?
Can we declare a constructor as final?
I want my class to be developed in such a way that no other class (even derived class) can create its objects. Define how can I do so?
Is a string literal?
What does indexof return in java?
What is run time allocation?
why are there separate wait and sleep methods? : Java thread
How do you do math powers in java?
What are nested classes in java?
Difference between this() and super() in java ?
What is finalize()?
Describe how to implement singleton design pattern in struts.
What are the main differences between the java platform and other platforms?
What is sortedmap in java?
What is empty list in java?