Skip to content

Instantly share code, notes, and snippets.

@linghuiluo
Last active August 2, 2019 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linghuiluo/0859d5d94ed082584711ae147227e854 to your computer and use it in GitHub Desktop.
Save linghuiluo/0859d5d94ed082584711ae147227e854 to your computer and use it in GitHub Desktop.
Java Type System

Java Type System

Concepts

  • Statically typed language: variables have definite types, it is a compile-time error to assign a value of an incompatible type to a variable, e.g., Java
  • Dynamically typed language: only check type compatiblity at runtime, e.g., JavaScript
  • Mutliple Inheritance of State, Implementation, and Type

Types in Java

  • Top-level types:
    • Primitive types
    • Reference types
      • Array
      • Class
        • enums are a special kind of of classes, implicitly extend java.lang.Enum
      • Interface
        • annotations are a special kind of interfaces, implicitly extend java.lang.annotation.Annotation
  • Nested types:
    • Static member types
    • Nonstatic member classes
    • Local classes
    • Anoymous classes

Inheritance in Java

  1. Three types of inheritance are supported for classes: single, multilevel and hierarchical. Let A, B, C being classes

    • single A <-- B
    • multilevel A <-- B <-- C
    • hierarchical (tree) A <-- B, A <-- C
  2. Multiple inheritance is NOT supported for classes

    • multiple A <-- C, B <-- C
    • why Java doesn’t support multiple inheritance?
      • the diamond problem: A <-- B, A <-- C, B <-- D, C<-- D
        • if B and C both have a method with same signature foo(), call D.foo will be a problem wether to call B's foo or C's foo method
      • simplicity:
        • multiple inheritance creates problem in casting, constructor chaining and so on.
        • very few scenarios need multiple inheritance
  3. Multiple inheritance is supported for Interfaces

    • default methods (introduced in Java 8, before interfaces only have abstract methods)

Generics

  • Type parameter <T> always stand in for reference types. It is not possible to use a primitive type as value for a type parameter.
    • bounded type parameter: <T extends Number>
    • mutiple bounds: <T extends A & B & C>
    • subtyping
  • Type Inference
  • Type Erasure
  • Wildcards <?>
    • bounded wildcards: <? extends Number>
    • subtyping

Lambda Expressions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment