• Post Reply Bookmark Topic Watch Topic
  • New Topic

is it illegal to have interface reference type referring to subclass (non-abstract) instance ?  RSS feed

 
Roshi Kumar
Greenhorn
Posts: 21
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is it illegal to have interface reference type referring to subclass (non-abstract) instance ?
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assailant Roshi wrote:is it illegal to have interface reference type referring to subclass (non-abstract) instance ?

What, you mean like:
List<X> list = new ArrayList<X>();
?

If so, the answer is no - indeed, it's a recommended approach (see programming to the interface).

If not, I don't understand the question.

Winston
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean something like this?

That's fine. In fact, that's the whole point. You can't have an interface variable referring to anything other than a subclass (or more properly: implementing class) instance, because you can't instantiate an interface directly.

Or did you mean something else?

Edit: or...what Winston said while I was still typing.
 
Roshi Kumar
Greenhorn
Posts: 21
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for you replies .

Matthew Brown , you got it what was my query . I got my answer thanks.

 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can declare any variable with a type and create an instance which is a subtype of that type, as you have already been told.
 
vikram setty
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This feature of using interface is the powerfull polymorphism feature in Java.. It is always advisible to use interface.

Example :
interface Animal{
void bark();
}

class Dog{
void bark(){
//perform bow bow here
}

}
class Cat{}{
void bark(){
//perform mew mew here
}
}

In the main method perform the following ..
Animal animal1 = new Dog();
Animal animal2= new Cat();

animal1.bar(); // bow bow is done for interface object
animal2.bark(); // mew mew is done for interface object
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!