DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Trending

  • Part 2: Securing and Scaling Goose-to-Java Agent Traffic With agentgateway
  • Kafka With Spring Boot: Introduction
  • Going All In On the JVM 25 Virtual Threads
  • Part 1: Building Governed MCP Tool Services With Quarkus LangChain4j and Goose

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Using Traits in Java 8

Using Traits in Java 8

In programming, traits have been around in Scala and PHP a while, but are relatively new through default methods in Java. Here's a quick example on how to use traits in Java 8!

By 
Emil Forslund
·
Jan. 29, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
32.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In one of my earlier articles I mentioned a programming component called "traits." These constructs have existed for many years in other programming languages like Scala and PHP but have only recently been available through default methods in Java. I will not go into the possibilities of using traits in this article, but I will show you a neat trick that you can use if you ever need to stream over a collection of different objects and separate those that fulfill a number of traits.

Say that you have two noun classes Person and Elephant. There is no reason really why people and elephants should belong to the same super class; elephants are intelligent four-legged creatures and most humans are not. You might still find the two of them in the same computer system and sometimes you even need to store them in the same collection. One way of operating on this collection of various living beings without making them share a common ancestor, (which would totally be just a theory), you can give them similar traits.

Take a look at this interface:

interface HasName extends Document {
    final String NAME = "name";

    default String getName() {
        return get(NAME);
    }

    default void setName(String name) {
        put(NAME, name);
    }
}

Using the Abstract Document Pattern presented earlier, the trait can set and get the attribute "name" from a map. If we now want to iterate over our collection of many living things that might or might not implement our specified traits, we can easily do it like this:


final Set<Object> livingBeings = new HashSet<>();

livingBeings.add(new Person(...));
livingBeings.add(new Person(...));
livingBeings.add(new Elephant(...));

livingBeings.stream()
    .filter(HasName.class::isInstance)
    .filter(HasAge.class::isInstance)
    .filter(HasWeight.class::isInstance)
    .map(p -> (HasName & HasAge & HasHeight) p)
    .forEach(p ->
        System.out.println(
            p.getName() + " is " +
            p.getAge() + " years old and weighs " +
            p.getWeight() + " pounds."
        )
    );

Using the and character (&) we can cast instances that implement all the required traits into a dynamic type, without them sharing an ancestor.

Trait (computer programming) Java (programming language)

Published at DZone with permission of Emil Forslund. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook