concept behavior in category java

appears as: behavior, behavior, The behavior, behaviors, behaviors
Java SE 11 Programmer I Certification Guide MEAP V03

This is an excerpt from Manning's book Java SE 11 Programmer I Certification Guide MEAP V03.

Java supports programming in multiple paradigms. Ever since its introduction, it supported programming with object-oriented paradigm by emulating real-life object definition and behavior. In real life, state and behavior are tied to an object. Java code is defined within classes, interfaces, or enums. Instances enables you to use their functionality.

All living beings inherit the characteristics and behaviors of their parents. The offspring of a fly looks and behaves like a fly, and that of a lion looks and behaves like a lion. But despite being similar to their parents, all offspring are also different and unique in their own ways. In addition, a single action may have different meanings for different beings. For example, the action “eat” has different meanings for a fly than a lion. A fly eats nectar, whereas a lion eats an antelope.

Something similar happens in Java. The concept of inheriting characteristics and behaviors from parents can be compared to classes inheriting variables and methods from a parent class. Being different and unique in one’s own way is similar to how a class can both inherit from a parent and define additional variables and methods. Single actions having different meanings can be compared to polymorphism in Java.

Let’s assume you’re supposed to store details of all Programmers and Managers in your office. Figure 10.1 shows the properties and behavior that you may have identified for a Programmer and a Manager, together with their representations as classes.

Figure 10.1 Properties and behavior of a Programmer and a Manager, together with their representations as classes
JUnit in Action MEAP V06

This is an excerpt from Manning's book JUnit in Action MEAP V06.

The JUnit team didn’t invent software testing or even unit tests, of course. Originally, the term unit test described a test that examined the behavior of a single unit of work: a class or a method. Over time, the use of the term unit test broadened. The Institute of Electrical and Electronics Engineers (IEEE), for example, has defined unit testing as “testing of individual hardware or software units or groups of related units” (emphasis added).[4]

  • Document expected behavior
  • Listing 20.13 Tests for the behavior of PremiumFlight
    public class AirportTest {
        [...]
     
        @DisplayName("Given there is a premium flight")                      #1
        @Nested                                                              #1
        class PremiumFlightTest {                                            #1
            private Flight premiumFlight;                                    #2
            private Passenger mike;                                          #2
            private Passenger james;                                         #2
     
            @BeforeEach
            void setUp() {
                premiumFlight = new PremiumFlight("3");                      #3
                mike = new Passenger("Mike", false);                         #3
                james = new Passenger("James", true);                        #3
            }
     
            @Nested                                                          #4
            @DisplayName("When we have a regular passenger")                 #4
            class RegularPassenger {                                         #4
               
                @Test                                                        #5
                @DisplayName("Then you cannot add or remove him              #5
                              from a premium flight")                        #5
                public void testPremiumFlightRegularPassenger() {            #5
                    assertAll("Verify all conditions for a regular passenger #6
                               and a premium flight",                        #6
                            () -> assertEquals(false,                        #7
                                  premiumFlight.addPassenger(mike)),         #7
                            () -> assertEquals(0,                            #7
                                  premiumFlight.getPassengersList().size()), #7
                            () -> assertEquals(false,                        #8
                                  premiumFlight.removePassenger(mike)),      #8
                            () -> assertEquals(0,                            #8
                                  premiumFlight.getPassengersList().size())  #8
                    );
                }
            }
     
            @Nested                                                          #9
            @DisplayName("When we have a VIP passenger")                     #9
            class VipPassenger {                                             #9
                @Test                                                        #10
                @DisplayName("Then you can add and remove him              #10
                              from a premium flight")                      #10
                public void testPremiumFlightVipPassenger() {              #10
                    assertAll("Verify all conditions for a VIP passenger   #11
                               and a premium flight",                      #11
                            () -> assertEquals(true,                       #12
                                  premiumFlight.addPassenger(james)),      #12
                            () -> assertEquals(1,                          #12
                                  premiumFlight.getPassengersList().size()), #12
                            () -> assertEquals(true,                       #13
                                  premiumFlight.removePassenger(james)),   #13
                            () -> assertEquals(0,                          #13
                                  premiumFlight.getPassengersList().size())  #13
                    );
                }
            }
        }
    }
    Modern Java in Action: Lambdas, streams, reactive and functional programming

    This is an excerpt from Manning's book Modern Java in Action: Lambdas, streams, reactive and functional programming.

    Now, as a direct parallel in Java, you want to tell a sort method to compare using a customized order. You could write a method compareUsingCustomerId to compare two invoice IDs, but, prior to Java 8, you couldn’t pass this method to another method! You could create a Comparator object to pass to the sort method as we showed at the start of this chapter, but this is verbose and obfuscates the idea of simply reusing an existing piece of behavior. Java 8 adds the ability to pass methods (your code) as arguments to other methods. Figure 1.3, based on figure 1.2, illustrates this idea. We also refer to this conceptually as behavior parameterization. Why is this important? The Streams API is built on the idea of passing code to parameterize the behavior of its operations, just as you passed compareUsingCustomerId to parameterize the behavior of sort.

    Figure 2.2. Parameterizing the behavior of filterApples and passing different filter strategies

    You may be wondering how to use lambda expressions with the observer design pattern. Notice that the various classes that implement the Observer interface all provide implementation for a single method: notify. They’re wrapping a piece of behavior to execute when a tweet arrives. Lambda expressions are designed specifically to remove that boilerplate. Instead of instantiating three observer objects explicitly, you can pass a lambda expression directly to represent the behavior to execute:

    f.registerObserver((String tweet) -> {
            if(tweet != null && tweet.contains("money")){
                System.out.println("Breaking news in NY! " + tweet);
            }
    });
    f.registerObserver((String tweet) -> {
            if(tweet != null && tweet.contains("queen")){
                System.out.println("Yet more news from London... " + tweet);
            }
    });

    Should you use lambda expressions all the time? The answer is no. In the example we described, lambda expressions work great because the behavior to execute is simple, so they’re helpful for removing boilerplate code. But the observers may be more complex; they could have state, define several methods, and the like. In those situations, you should stick with classes.

    Remember that lambda expressions generate an instance of a functional interface. As a result, you can test the behavior of that instance. Here, you can call the compare method on the Comparator object compareByXAndThenY with different arguments to test whether its behavior is as intended:

    OCA Java SE 8 Programmer I Certification Guide

    This is an excerpt from Manning's book OCA Java SE 8 Programmer I Certification Guide.

    Java code can be executed on multiple systems without recompilation. Java code is compiled into bytecode, to be executed by a virtual machine—the Java Virtual Machine (JVM). A JVM is installed on platforms with different OSs like Windows, Mac, or Linux. A JVM interprets bytecodes to machine-specific instructions for execution. The implementation details of a JVM are machine-dependent and might differ across platforms, but all of them interpret the same bytecode in a similar manner. Bytecode generated by a Java compiler is supported by all platforms with a JVM.

    All living beings inherit the characteristics and behaviors of their parents. The offspring of a fly looks and behaves like a fly, and that of a lion looks and behaves like a lion. But despite being similar to their parents, all offspring are also different and unique in their own ways. In addition, a single action may have different meanings for different beings. For example, the action “eat” has different meanings for a fly than a lion. A fly eats nectar, whereas a lion eats an antelope.

    Something similar happens in Java. The concept of inheriting characteristics and behaviors from parents can be compared to classes inheriting variables and methods from a parent class. Being different and unique in one’s own way is similar to how a class can both inherit from a parent and define additional variables and methods. Single actions having different meanings can be compared to polymorphism in Java.

    Let’s assume you’re supposed to store details of all Programmers and Managers in your office. Figure 6.1 shows the properties and behavior that you may have identified for a Programmer and a Manager, together with their representations as classes.

    Figure 6.1. Properties and behavior of a Programmer and a Manager, together with their representations as classes

    The default methods are also referred to as defender or virtual extension methods. But the most popular term to refer them is default methods because the default keyword is used to identify them.

    Java 8 in Action: Lambdas, streams, and functional-style programming

    This is an excerpt from Manning's book Java 8 in Action: Lambdas, streams, and functional-style programming.

    Now, as a direct parallel in Java, you want to tell a sort method to compare using a customized order. You could write a method compareUsingCustomerId to compare two invoice IDs but, prior to Java 8, you couldn’t pass this method to another method! You could create a Comparator object to pass to the sort method as we showed at the start of this chapter, but this is verbose and obfuscates the idea of simply reusing an existing piece of behavior. Java 8 adds the ability to pass methods (your code) as arguments to other methods. Figure 1.3, based on figure 1.2, illustrates this idea. We also refer to this conceptually as behavior parameterization. Why is this important? The Streams API is built on the idea of passing code to parameterize the behavior of its operations, just as you passed compareUsingCustomerId to parameterize the behavior of sort.

    Figure 2.2. Parameterizing the behavior of filterApples and passing different filter strategies

    You may be wondering how lambda expressions are useful with the observer design pattern. Notice that the different classes implementing the Observer interface are all providing implementation for a single method: notify. They’re all just wrapping a piece of behavior to execute when a tweet arrives! Lambda expressions are designed specifically to remove that boilerplate. Instead of instantiating three observer objects explicitly, you can pass a lambda expression directly to represent the behavior to execute:

    f.registerObserver((String tweet) -> {
            if(tweet != null && tweet.contains("money")){
                System.out.println("Breaking news in NY! " + tweet);
            }
    });
    
    f.registerObserver((String tweet) -> {
            if(tweet != null && tweet.contains("queen")){
                System.out.println("Yet another news in London... " + tweet);
            }
    });

    Should you use lambda expressions all the time? The answer is no! In the example we described, lambda expressions work great because the behavior to execute is simple, so they’re helpful to remove boilerplate code. But the observers may be more complex: they could have state, define several methods, and the like. In those situations, you should stick with classes.

    Remember that lambda expressions generate an instance of a functional interface. As a result, you can test the behavior of that instance. Here, you can now call the method compare on the Comparator object compareByXAndThenY with different arguments to test that its behavior is as intended:

    Portlets in Action

    This is an excerpt from Manning's book Portlets in Action.

    In the service-oriented architecture (SOA), service orchestration (or collaboration) makes it possible to develop applications from existing services. As portlets represent services and are pluggable components, you can get plug and play behavior using portlets. Because portlets can interact with each other at the user interface layer (a process referred to as inter-portlet communication), they play a crucial role in developing SOA applications.

    Personalization of content plays an important role in enriching the user experience. It lets your application’s users specify the content that they’re interested in, and the application in turn honors each user’s preferences. Application personalization isn’t limited to personalizing content but can also apply to customizing the behavior of the application. For instance, the Gmail portlet in the iGoogle portal allows users to specify the number of emails they want to view in the portlet (personalization of content) and whether they want to open a selected email in the same or a new browser window (personalization of behavior), as shown in Figure 10.1.

    Figure 10.1. The Gmail portlet provides personalization options for portlet content and behavior.

    10.7.2. Personalizing content and behavior

    So far in this chapter, you’ve learned about saving and retrieving preferences to and from the persistent store. The real value of the preferences shows up when you use them to customize the content and behavior of your portlet. In this section, we’ll look at how the Book Catalog portlet makes use of preferences to customize its behavior and content.

    Table 10.2 revisits the preferences defined at the beginning of this chapter and describes their effect on the content and behavior of the Book Catalog portlet.

    Table 10.2. Book Catalog preferences

    Preference

    Effect on content and behavior

    Preferred Category Allows a user to personalize the Book Catalog portlet to show books from specified categories. For instance, if the user has chosen to view books in the Java and .NET categories, only books related to those categories are shown to the user when they visit the portal page.
    Search Type Allows a user to choose between case-insensitive and case-sensitive searches for books.
    Maximum Number of Books to Show Allows a user to specify the number of books that will be shown in the Book Catalog portlet. By default, the Book Catalog portlet shows up to 1000 books on the page.
    Greetings Message Represents the greetings message that’s shown to the user on the portlet’s home page. It can’t be changed by the user and is shown as a read-only option.
    Preferred Book ISBN Number If the user specifies one or more preferred books, the books are shown highlighted, on a yellow background, on the home page of the Book Catalog portlet.

    In this section, we’ll look at how content is personalized based on the Preferred Category preference and how behavior is personalized based on the Search Type preference. The rest of the preferences in the Book Catalog portlet are implemented along similar lines.

    sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest