File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface and Implementation

 
Lucky Singh
Ranch Hand
Posts: 125
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have a package ABC. In that package, I have an interface, an implementation for the interface and a Driver that uses tests the application.

public interface Greetings {
public void sayHi();
public void sayBye();
}

public class Implementation {
public void sayHi() {
//do something
}

public void sayBye() {
//do something
}

public boolean check() {
//return a bolean value
}
}

public class Driver {
public static void main(String args[])
{
Greetings obj = new Impl();
boolean ret = obj.check(); ---------ERROR
obj.sayHi();
obj.sayBye();
}
}

The object obviously does not recognize the method check. How do I overcome this problem so that I could use check() in the Driver but not include it in my interface?
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two ways, either use you implementation directly:

or cast the object before using it:
 
Lucky Singh
Ranch Hand
Posts: 125
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your response. Solution 1 seems fine.
I would however like to use soultion 2. When I tried it, I got an error-
Cannot convert IMPL to type boolean. Is there any way, I can use solution 2 or something similar?
 
Tony Morris
Ranch Hand
Posts: 1608
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Lucky Singh:
Hi, I have a package ABC. In that package, I have an interface, an implementation for the interface and a Driver that uses tests the application.



The object obviously does not recognize the method check. How do I overcome this problem so that I could use check() in the Driver but not include it in my interface?


Simply using interface inheritance, or horribly using a cast to a concrete type.


Now your implementation should implement the CheckableGreetings interface (if that indeed what it should do). Note that your provided source code sample contains errors, so I won't try to fix them based on assumptions. I hope the point is clear. Casting can always be avoided with a more approopriate abstraction.
[ August 24, 2005: Message edited by: Tony Morris ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic