tags:

views:

257

answers:

5

In C#, it's common to have methods like this:

public IPerson GetPerson()
{
  // do stuff
  return new Person(..);
}

where "IPerson" is an interface used by Person, SpecialPerson, etc. In other words, although the method above returns a Person, a strategy pattern could be implemented such that a SpecialPerson is returned in lieu of a Person, provided they all use the IPerson interface.

Is this sort of thing possible in Java?

+8  A: 

Yes. Java has interfaces too.

matt b
+3  A: 

I believe it is pretty much the same, other than Java uses the "implements" keyword for interfaces.

Jimmeh
+2  A: 

Yes, Java has interfaces just like C#: public interface IPerson { ... }

Steven
+1  A: 

The Java equivalent would be:

public Person getPerson()
{
  // do stuff
  return new SpecialPerson(..);
}

Where Person is a Java interface (prefixing interface names with the letter "I" is a convention from COM programming, thus not appropriate for Java).

John Topley
I use the I prefix convention in Java so that it's easier to identify file types without having to open them (like in the Eclipse browsser). I also use A for abstract classes. Just helps me sort through things. Nice thing about conventions is that you can use your own.
Dopyiii
If you design right, you should not have to care that you have an interface type or another type.
Martin OConnor
@Martin - exactly!
John Topley
+3  A: 

Yes, it's pretty much the same... For example:

// Interface
public interface IPerson {
    public String getName();
}

// Implementation of interface - NB "implements" keyword
public class Person implements IPerson {
    private final String myName;

    public Person(String name) {
        myName = name;
    }

    public String getName() {
        return myName;
    }
}

// Method returning interface
public IPerson getPerson(String name) {
    return new Person(name);
}