concept type in category java

appears as: type, type, types, The type, types, A type, The types
Java SE 11 Programmer I Certification Guide

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

Java is a strongly typed language, which implies that the compiler knows the type of all its variables. Data type checks during compilation prevent unwanted surprises (read exceptions and errors) at runtime.

  • #4 also prints Employee. The type of the variable programmer is Employee. Because the variables are bound at compile time, the type of the object that’s referenced by the variable emp doesn’t make a difference. programmer.name will access the variable name defined in the class Employee.
  • #5 prints Employee. Because the type of the reference variable emp and the type of object referenced by it are the same (Employee), there’s no confusion with the method call.
  • Here’s some code that demonstrates that an object of the class HRExecutive can be referred to using a variable of type HRExecutive:

    class Office {
        public static void main(String args[]) {
            HRExecutive hr = new HRExecutive();       #A
        }
    }

    You can access fields and methods defined in the class Employee, the class HRExecutive, and the interface Interviewer using the variable hr (with the type HRExecutive), as follows:

    Figure 10.10 A variable of type Interviewer can see only the members defined in the interface Interviewer.
    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.

    Java 8 adds a Streams API (note the uppercase S) in java.util.stream based on this idea; Stream<T> is a sequence of items of type T. You can think of it as a fancy iterator for now. The Streams API has many methods that can be chained to form a complex pipeline just like Unix commands were chained in the previous example.

    Multiple inheritance of types

    Here, ArrayList is extending one class and directly implementing four interfaces. As a result, an ArrayList is a direct subtype of seven types: AbstractList, List, RandomAccess, Cloneable, Serializable, Iterable, and Collection. In a sense, you already have multiple inheritance of types.

    Listing C.6. Putting the StreamForker to work
    Stream<Dish> menuStream = menu.stream();
    
    StreamForker.Results results = new StreamForker<Dish>(menuStream)
            .fork("shortMenu", s -> s.map(Dish::getName)
                                     .collect(joining(", ")))
            .fork("totalCalories", s -> s.mapToInt(Dish::getCalories).sum())
            .fork("mostCaloricDish", s -> s.collect(reducing(
                    (d1, d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2))
                    .get())
            .fork("dishesByType", s -> s.collect(groupingBy(Dish::getType)))
            .getResults();
    
    String shortMenu = results.get("shortMenu");
    int totalCalories = results.get("totalCalories");
    Dish mostCaloricDish = results.get("mostCaloricDish");
    Map<Dish.Type, List<Dish>> dishesByType = results.get("dishesByType");
    
    System.out.println("Short menu: " + shortMenu);
    System.out.println("Total calories: " + totalCalories);
    System.out.println("Most caloric dish: " + mostCaloricDish);
    System.out.println("Dishes by type: " + dishesByType);
    Java Testing with Spock

    This is an excerpt from Manning's book Java Testing with Spock.

    A bug/issue that reaches production code can have a profound effect, depending on the type of software. For example, if your software is a mobile application for tracking daily intake of calories, you can sleep easily each night knowing that any issues found by users will only inconvenience them, and in the worst case they’ll delete your application from their mobile phones (if they get really angry about the problems). But if, for example, you’re writing software that manages hotel reservations, consequences are more serious. Critical issues will result in customer anger, brand damage for the hotel, and probable future financial losses.

    One of the first questions every Java developer asks when seeing a Spock test is about the use of the def keyword. This keyword is one of the central concepts of Groovy that characterize it as dynamically typed.[5] You can find all the details in the Groovy specification if you feel adventurous, but for the purpose of writing Spock tests, the meaning of def is “I won’t declare a type here; please do it automatically for me.”

    Listing 6.21. Verifying the type of arguments
    The Java Module System

    This is an excerpt from Manning's book The Java Module System.

    One example is the lack of meaningful encapsulation across JARs: all public types are freely accessible by all code in the same application. This makes it easy to inadvertently depend on types in a library that its maintainers considered implementation details and never polished for public use. They likely hid the types in a package called internal or impl, but that doesn’t stop us from importing them anyway.

    In section 3.2, we explored in depth how requires directives establish dependencies between modules and how the module system uses them to create reads edges (eventually resulting in the module graph, as sections 3.4.1 and 3.4.2 show). In section 3.3, you saw that accessibility is based on these edges, and to access a type, the accessing module must read the module containing the type (the type must also be public and the package exported, but that isn’t relevant here).

    It looks like it needs the types ServiceObserver and DiagnosticDataPoint. Both are in monitor.observer, so what happens if monitor.peek doesn’t require monitor.observer? It can’t access its types, resulting in compile errors. As you saw when we discussed the encapsulation of transitive dependencies in section 3.3.2, this is a feature of the module system.

    Here it’s an impediment, though. Without the types from monitor.observer, monitor.observer.alpha is effectively useless; and every module that wants to use it has to read monitor.observer as well. (This is shown in figure 11.1.) Does every module using monitor.observer.alpha have to require monitor.observer, too?

    That’s not a comfortable solution. If only there was another mechanism to establish readability and thus unlock access to types.

    Figure 11.1 The module peek uses observer.alpha, which uses types from observer in its public API. If peek doesn’t require observer (left), it can’t read its types, making observer.alpha useless. With regular requires directives, the only way around that is to have peek also require observer (right), which becomes cumbersome when more modules are involved.

    c11_01.png

    Figure 11.2 Three modules are involved in the problem of exposed dependencies: the innocent one that provides some types (exposed; right), the guilty one using those types in its public API (exposing; middle), and the impacted one having to accesses the innocent’s types (depending; left).

    c11_02.eps

    What happens in the previous example is common. A module exposing depends on some module exposed, but uses types from exposed in its own public API (as defined in section 3.3). In such cases, exposing is said to expose its dependency on exposed to its clients because they also need to depend on exposed in order to use exposing.

    Get Programming with Java

    This is an excerpt from Manning's book Get Programming with Java.

  • Type in code, compile it, and run it using the IDE
  • Listing 12.2 Book Class
    1.    package acmepublishing;   //#A
     2.    public class Book {      
     3.        private int authorID;   //#B
     4.        private String bookTitle;  //#B
     5.       private char bookType = 'h'; //h-hardcopy, e-ebook  //#B
     6.        private int numPages;  //#B
     7.        public Book(int authorID, String bookTitle, char bookType, int numPages) {
     8.            this.authorID = authorID;
     9.            this.bookTitle = bookTitle;
     10.           if(bookType == 'e' || bookType == 'h' || bookType == 'b')  //#C
     11.               this.bookType = bookType;    //#C
     12.           else
     13.               this.bookType = 'h'; //if an invalid book type is entered, //#C
     14.                                    //it is set to hard copy   //#C
     15.           this.numPages = numPages; 
     16.       }
     17.       public int getAuthorID() {return authorID;}
     18.       //Getter and Setter methods go here
     19.       @Override
     20.       public String toString() {   //#D
     21.           String type;
     22.           if(bookType == 'e')
     23.               type = "Electronic copy only";
     24.           else if(bookType == 'h')
     25.               type = "Hard copy only";
     26.           else
     27.               type = "Both hard copy and electronic";
     28.           return "\n\nBook Info: \nAuthor ID: " + authorID + "\nBook Title: "+
     29.                   bookTitle + "\nBook Type: " + bookType + "\nNumber of Pages: "
     30.                   + numPages;
     31.   }    //#D
     32.   }
    OCA Java SE 8 Programmer I Certification Guide

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

    Explanation: The rules you need to follow to assign a value to an array element are the same rules you follow when you assign an object to a reference variable. Because the type of array interviewer is Interviewer, you can assign objects of classes that implement this interface. The inheritance of classes Employee, Manager, and HRExecutive and the interface Interviewer are shown in figure A.5.

    Figure 6.18. A variable of type Employee can see only the members defined in the class Employee.

    The output of the preceding code is as follows:

    private void method2(int age) {
        if (age > 30)
            throw Exception();
    }
    Functional Programming in Java: How functional techniques improve your Java programs

    This is an excerpt from Manning's book Functional Programming in Java: How functional techniques improve your Java programs.

    The compiler is saying that it couldn’t infer the real types for the T, U, and V type parameters, so it used Object for all three. But the square and triple functions have types Function<Integer, Integer>. If you think that this is enough information to infer the T, U, and V types, then you’re smarter than Java! Java tried to go the other way around, casting a Function<Integer, Integer> into a Function<Object, Object>. And although an Integer is an Object, a Function<Integer, Integer> isn’t a Function <Object, Object>. These two types aren’t related because types are invariant in Java. For the cast to work, the types should have been covariant, but Java doesn’t know about variance.

    Don’t trust names. Trust types. Types don’t lie. Types are your friends!

    public class Deposit implements Input {
    
      private final int amount;
    
      public Deposit(int amount) {
        super();
        this.amount = amount;
      }
    
      @Override
      public Type type() {
        return Type.DEPOSIT;
      }
    
      @Override
      public boolean isDeposit() {
        return true;
      }
    
      @Override
      public boolean isWithdraw() {
        return false;
      }
      @Override
      public int getAmount() {
        return this.amount;
      }
    }
    
    public class Withdraw implements Input {
    
      private final int amount;
    
      public Withdraw(int amount) {
        super();
        this.amount = amount;
      }
    
      @Override
      public Type type() {
        return Type.WITHDRAW;
      }
    
      @Override
      public boolean isDeposit() {
        return false;
      }
    
      @Override
      public boolean isWithdraw() {
        return true;
      }
    
      @Override
      public int getAmount() {
        return this.amount;
      }
    }
    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.

    Java 8 adds a Streams API (note the uppercase S) in java.util.stream based on this idea; Stream<T> is a sequence of items of type T. You can think of it as a fancy iterator for now. The Streams API has many methods that can be chained to form a complex pipeline just like Unix commands were chained in the previous example.

    Multiple inheritance of types

    Here, ArrayList is extending one class and implementing six interfaces. As a result, an ArrayList is a direct subtype of seven types: AbstractList, List, RandomAccess, Cloneable, Serializable, Iterable, and Collection. So in a sense we already have multiple inheritance of types.

    Listing C.6. Putting the StreamForker to work
    Stream<Dish> menuStream = menu.stream(); StreamForker.Results results = new StreamForker<Dish>(menuStream) .fork("shortMenu", s -> s.map(Dish::getName) .collect(joining(", "))) .fork("totalCalories", s -> s.mapToInt(Dish::getCalories).sum()) .fork("mostCaloricDish", s -> s.collect(reducing( (d1, d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2)) .get()) .fork("dishesByType", s -> s.collect(groupingBy(Dish::getType))) .getResults(); String shortMenu = results.get("shortMenu"); int totalCalories = results.get("totalCalories"); Dish mostCaloricDish = results.get("mostCaloricDish"); Map<Dish.Type, List<Dish>> dishesByType = results.get("dishesByType"); System.out.println("Short menu: " + shortMenu); System.out.println("Total calories: " + totalCalories); System.out.println("Most caloric dish: " + mostCaloricDish); System.out.println("Dishes by type: " + dishesByType);
    Spring Integration in Action

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

    We live in an event-driven world. Throughout each day, we’re continuously bombarded by phone calls, emails, and instant messages. As if we’re not distracted enough by all of this, we also subscribe to RSS feeds and sign up for Twitter accounts and other social media sites that add to the overall event noise. In fact, technological progress seems to drive a steady increase in the number and types of events we’re expected to handle. In today’s world of hyperconnectivity, it’s a wonder we can ever focus and get any real work done. What saves us from such event-driven paralysis is that we can respond to most events and messages at our convenience. Like a return address on an envelope, events usually carry enough information for us to know how and where to respond.

    A few different kinds of adaptation are required depending on the type of channel and the role of the handler component being connected to that channel. If the channel is subscribable, the handler is invoked within the thread of the sender or by the channel’s TaskExecutor if one is configured. For such a channel, no polling is required. If on the other hand the channel is one that buffers messages in a queue, such as a QueueChannel, polling is necessary.

    The Well-Grounded Java Developer

    This is an excerpt from Manning's book The Well-Grounded Java Developer.

    The compiler will attempt to create an array to contain hm1 and hm2, but the type of the array should strictly be one of the forbidden array types. Faced with this dilemma, the compiler cheats and breaks its own rule about the forbidden array of generic type. It creates the array instance, but grumbles about it, producing a compiler warning that mutters darkly about “unchecked or unsafe operations.”

  • You don’t have to declare the type of hello—the compiler just works it out.
  • This is also relatively unsurprising. In the example where you don’t create kitties as a temporary variable, Scala type-infers the type of the queue to be Queue[Cat], and then accepts michael as being of a suitable type—BengalKitten—to be added to the queue. In the second example, you explicitly provide the type of kitties. This means that Scala is unable to use type inference and so can’t make the parameters match.

    Griffon in Action

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

    Tied to a particular structure, an application should be able to manage all aspects of its life cycle: what to do to bootstrap itself, initialize its components (perhaps by type, layer, or responsibility), allocate resources, and bind all event handlers, just to name a few common tasks. Take for example LimeWire, a popular Java Swing application used to share files on peer-to-peer networks. Can you imagine the phases the application has to undertake to work properly? What about another popular Java Swing application, NetBeans? Surely the people behind its design have given a lot of thought to how the application should control its life cycle. What would it take for you to achieve the same thing?

    Let’s pause for a moment and review all you’ve discovered about Griffon so far. First, you’ve learned that all Griffon applications share the same basic structure. You also know that application artifacts are organized by type and responsibility in specific folders on disk. In addition, the MVC pattern is the cornerstone for Griffon’s MVC groups. These, in turn, can be extended by adding other MVC groups within them as members. Finally, you know that you should remember to take threading into account. And you know that all artifacts are glued together via the Groovy language.

    In Abbot, for example, you must locate a UI component by conventional means, such as by inspecting a container’s hierarchy or accessing a direct reference available in the container instance. Alternatively, you can use Abbot’s finder utilities. Next you instantiate a particular Abbot tester that knows how to work with the type of component you want to test. Finally, you invoke the desired behavior on the tester and assert the component’s state. Here’s a snippet of a ComponentTestFixture that shows how it can be done:

    JTextField textField = getFinder().
        find(new ClassMatcher(JTextField))
    JButton button = getFinder().find(new Matcher() {
       public boolean matches(Component c) {
          c instanceof JButton && c.text == "Search"
       }
    })
    JTextArea textArea = getFinder().find(new ClassMatcher(JTextArea))
    JTextComponentTester tester = new JtextComponentTester()
    tester.actionEnterText(textField, "Griffon")
    tester.actionClick(button)
    assert "Griffon is cool!" == textArea.text

    It works, but it’s a bit verbose. We’ve highlighted two parts of the code. The first shows one of the many options that Abbot exposes to locate a component; this one locates a JTextField by type. The second highlighted bit creates an Abbot helper object with the responsibility of sending stimuli to the located UI components. Perhaps if the finders were wrapped with a friendlier abstraction, you would be able to write less code. Sadly, that abstraction isn’t provided by default by Abbot.

    You should see a few messages about the application code being compiled (if it wasn’t up to date already) and then a few more regarding the test code being compiled. Then you’ll see a special block of text that specifically mentions the type and number of tests being run. Here’s the output of running unit tests on the Sample application:

    AspectJ in Action, Second Edition

    This is an excerpt from Manning's book AspectJ in Action, Second Edition.

    Abstraction, by its nature, hides the details. In software systems, higher levels of abstraction always mean that less information is available at the code level. Looking at a code segment doesn’t tell you the whole story that will unfold during system execution. For example, in OOP, due to polymorphic methods, you can’t tell the exact method that will be executed at runtime, because the choice of method is based on the type of the object, not the static type of the declared variable. This makes analyzing program flow a complex task. Even in procedural languages such as C, if you use function pointers, the program flow isn’t static and requires some effort to be understood.

    Figure 3.2. Relationship between join points, signature patterns, and pointcuts. Types, methods, and fields all have a signature pattern associated with them (shown with a gray background); it’s a way to identify a program element. Pointcuts use signature patterns to select the associated join points.

    Annotations specify metadata (additional data or information) about the element they’re annotating. For example, a type may carry an annotation such as @Entity that indicates that the type is persistent. AspectJ allows the use of annotations in type signature patterns. Because the annotations are types too, the type signature patterns in table 3.2 apply to them as well.

    These pointcuts select join points based on the types of the objects at execution time. The pointcuts select join points that match either the type of this, which is the current execution object, or the target object, which is the object on which the method is being called.