Cody
Cody

Reputation: 8964

What is this called? Is this a design pattern or a convention? (Interfaces / classes)

Lately when I have been looking at other code, I have noticed that I see one file with multiple interfaces and classes - sometimes extending those interfaces.

What is this called? Is this good / bad practice?

Also, if it is good practice, is there any documentation on how to properly utilize this? If not, is there some other documentation on using interfaces most efficient and the 'best practices' for them?

One place they are used is here: Google IoSched

Upvotes: 2

Views: 121

Answers (4)

Ted Hopp
Ted Hopp

Reputation: 234857

The term for a class that is a member of another class is a nested class. As the tutorial explains, this is done for several reasons:

  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.

This technique is often used when the nested class is closely tied to the enclosing class. (For instance, Map.Entry is a nested class of Map and Character.UnicodeBlock is a nested class of Character.)

Nested interfaces serve the same function—to define an interface that is closely connected to the enclosing class.

Upvotes: 1

Shaun
Shaun

Reputation: 2476

These are inner interfaces (which are inherently static inner interfaces, even though they aren't explicitly marked with the modifier static. They are used to define an interface that is so closely connected to the class it's defined within that it wouldn't be worthwhile defining it outside that class.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160321

They're inner (nested) classes/interfaces, used when the classes or interfaces make no sense without the containing class or are generally accessed only by the containing class, or in a context tightly coupled to the containing class.

They exist in JSE as well, e.g., Map.Entry.

Upvotes: 2

MK.
MK.

Reputation: 34597

This looks like enums using interfaces pattern (or rather anti-pattern now). Now that Java has enums and static imports there is no reason to use this.

Upvotes: 3

Related Questions