Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

clear my doubt

 
VIGNESHWAR VISWANATHAN
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
new can be used with interface to return the object of other class or not....
please share your views... thank you
 
John Stone
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't understand your question.

Are you reffering to creating anonymous classes using interfaces or to upcasting created objects to interface they implement?
 
raj malhotra
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Please specify proper subject line and make sure you read your message atleast once before posting .
Thanks
 
VIGNESHWAR VISWANATHAN
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
interface Animal
{
void soundOff();
}
class Elephant implements Animal
{
public void soundOff()
{
System.out.println("Trumphet");
}
}
class Lion implements Animal
{
public void soundOff()
{
System.out.println("Roar");
}
}
class Alpha1
{
static Animal get(String choice)
{
if(choice.equalsIgnoreCase("meat eater"))
{
return new Lion();
}
else
{
return new Elephant();
}}}

which compiles?
A. new Animal().soundOff();
B.Elephant e=new Alpha1();
C.Lion 1=Alpha.get("meat eater");
D.new Alpha1().get("veggie").soundOff();

this is the code... here i have learnt that in option A. you cannot use new ininterface...Is it so?
 
John Stone
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it is, you can not create instance of interface. (Interface methods have no body, what would they do?)
 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

VIGNESHWAR

There are no constructors for interfaces.So can't create an object.


Thanks

Anil Kumar
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15485
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by VIGNESHWAR VISWANATHAN:
which compiles?
A. new Animal().soundOff();
B.Elephant e=new Alpha1();
C.Lion 1=Alpha.get("meat eater");
D.new Alpha1().get("veggie").soundOff();

Such questions can easily be answered by simply trying it out. Write a small Java program with the lines mentioned under options A to D, try to compile it and see what the compiler says.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic