Quick Index
Overview


In the real world, entities/things are typically multiple types.

For example, Asha might be:


Java interfaces are a way objects can be multiple types. This may also be referred to as multiple inheritance.

Concept


Let's say you have coded a class StudentClub that models a club with a name and a list of member names.

Another coder in your office has coded "CoolProgram" that uses "Group" type objects.

You would like to be able to plug StudentClub objects into CoolProgram?

You need a way for an object to be be multiple types -- i.e. both a StudentClub type and a Group type.

Let's look at an example.

Group Example


Group Interface
This is what a Java interface looks like -- method headers with no implementation.
/**
I am a "Group" interface.

I model any object that can call itself a "group".

If you want to be a "Group" type you must implement
the methods below.
*/

public interface Group {

	public String title();
	public int size();

}
StudentClub -- Class That Implements 'Group'
This is all that class StudentClub needs to do to become a "Group":

  • Add "implements Group" to the class header
  • Implement all the methods declared in the "Group" interface

StudentClub is now a StudentClub (naturally) and a "Group". It is multiple types.
public class StudentClub implements Group  {
	public String name;
	public List<String> members;

	public String title()  {
		return this.name;
	}

	public int size()  {
		return this.members.size();
	}

	//etc (more code follows)

}


Try These Examples


Group Java Interface -- 👉🏼 Try It

Shippable Java Interface -- 👉🏼 Try It

SummaryObject Java Interface -- 👉🏼 Try It

TouristAttraction Java Interface -- 👉🏼 Try It

Download All Examples


Download examples