Results 1 to 5 of 5
  1. #1
    guro is offline Member
    Join Date
    Mar 2009
    Posts
    2
    Rep Power
    0

    Default Interface as a type!

    I have a question about java interface. Assume that:
    public interface intf_X{
    // abstract methods define
    }

    Since intf_X can be used as a type (e.g. intf_X x1;) can we use intf_X as a return type from a function (I mean: intf_X foo()) and in which case we can use it? Can you give a simple example?

    Thanks

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,313
    Blog Entries
    1
    Rep Power
    31

    Default

    the best test is already in your hands: your friendly Java compiler!

    Why not create a simple interface and see if you can return it from a method? See if it compiles?

  3. #3
    Sylar's Avatar
    Sylar is offline Member
    Join Date
    Mar 2009
    Location
    Odessa, Texas
    Posts
    16
    Rep Power
    0

    Default

    Agree ^

    Its best if you discover it first hand.

  4. #4
    guro is offline Member
    Join Date
    Mar 2009
    Posts
    2
    Rep Power
    0

    Default

    Hello all,
    I did the following test and gain a bit understanding of interface. It compiles just fine.

    public interface X_intf{
    void X_method();
    }

    public class X_impl{
    // Constructor
    public X_impl(){
    // Do something
    }

    void X_method(){
    // Do something
    }
    }

    public interface MyInterface{
    X_intf getInfo();
    }

    public class MyClass implements MyInterface(){
    X_intf x;

    // Constructor
    public MyClass(X_intf x){
    this.x = x;
    }

    public X_intf getInfo(){
    return x;
    }
    }

    // in Main.java
    X_impl x_var = new X_impl();
    MyClass var1 = new MyClass(x);

    System.out.println(var1.getInfo().X_method());

  5. #5
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    11

    Default

    Yes. Interfaces can be used everywhere classes can be used (well, except that interfaces obviously have no constructors, and a few other restrictions!).

    Therein lies the power of an interface.

Similar Threads

  1. using instanceof to get Object type and parent type?
    By xcallmejudasx in forum New To Java
    Replies: 2
    Last Post: 11-06-2008, 06:24 PM
  2. [SOLVED] Cast string type to int type
    By GilaMonster in forum New To Java
    Replies: 9
    Last Post: 09-17-2008, 10:43 AM
  3. i can't understand using interface as a type
    By sireesha in forum New To Java
    Replies: 3
    Last Post: 11-20-2007, 10:07 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •