+ All Categories
Home > Documents > M14 - Advanced Language Features

M14 - Advanced Language Features

Date post: 02-Jun-2018
Category:
Upload: shaharukh-nadaf
View: 237 times
Download: 0 times
Share this document with a friend

of 24

Transcript
  • 8/10/2019 M14 - Advanced Language Features

    1/24

    Module 14: Additional Language Features

    Java Course

  • 8/10/2019 M14 - Advanced Language Features

    2/24

    2

    Module Objectives

    At the end of this module, participants will beable to:

    Define inner and anonymous classes

    Use Java generics

    Use enhance for-loop

    Describe how auto-boxing works

    Declare and make use of enumerations

    Declare methods and call methods with variable

    arguments

    Describe what static imports are for and howthey are used

    Explain how to use annotations

  • 8/10/2019 M14 - Advanced Language Features

    3/24

    3

    Inner and Anonymous Classes

    An inner class is a class declared within another class and canbe assigned an access modifier just like other class fields.

    An inner class has private access to the other fields of a class.

    There are two additional types of inner classes:

    local inner classan inner class within the body of a method.

    anonymous inner classesaninner class within the body of a method

    without naming it.

    ** Refer to the InnerClassSample.java and AnonInnerClassSample.java

    sample code

  • 8/10/2019 M14 - Advanced Language Features

    4/24

    4

    Generics allow classes or methods to declare during compiletime what type of objects they are meant to work with without

    having the class/method definition.

    Generics is one way of avoiding lengthy type casts in order to

    convert objects form one class to another.

    ** Refer to the GenericSample.java and EmployeeGenerics.java sample

    code

    Generics Overview

  • 8/10/2019 M14 - Advanced Language Features

    5/24

    5

    The class below declares that the can be parameterized bya class type during instantiation.

    publ icclassGenericSample {

    pr ivateE field;

    publ icvo idsetValue(E arg){

    th is.field =arg;

    }

    publ icE getValue(){

    returnfield;

    }

    }

    The following instantiates the class parameterized with a String.

    GenericSample g1 = newGenericSample();

    Generics Overview (cont.)

  • 8/10/2019 M14 - Advanced Language Features

    6/24

    6

    That particular instance will be created as if GenericSamplehadString in all places where E was placed.

    Many collections have been updated to take advantage of

    generics instead of using the generic Objectclass.

    List stringList = new ArrayList;

    stringList.add(Hello);

    stringList.add(new Integer(1)); //Illegal now with generics, but previously legal without using generics

    Generics Overview (cont.)

  • 8/10/2019 M14 - Advanced Language Features

    7/247

    Wildcard notations can be used to indicate the boundaries in a classhierarchy.

    The notation indicates that type is a subclassof Class Type.

    //Allows only sublasses of Number to be passed

    pub l icclassGenericSample {privateE field;

    pub l icvo idsetValue(E arg){

    th is.field =arg;

    }

    pub l icE getValue(){

    returnfield;

    }}

    ** Refer to the UpperBound.java sample code

    Bounded Type Parameters

  • 8/10/2019 M14 - Advanced Language Features

    8/248

    The notation ? can be used to indicate an unknown class. Thisis similar to using Object as a parameter.

    The notation

  • 8/10/2019 M14 - Advanced Language Features

    9/249

    Enhanced For-Loop

    Enhanced For-Loopreduces the need for iterators when going throughan array or a collection.

    It allows you to iterate through a collection without having to create an

    Iterator or without having to calculate beginning and end conditions for

    a counter variable.

    for( var : list){

    //

    }

    in t[] sqr = {0,1,4,9,16,25};

    fo r(in ti : sqr) {

    System.out.printf(ii);

    }

    }

    ** Refer to the EnhancedForLoop.java sample code

  • 8/10/2019 M14 - Advanced Language Features

    10/2410

    Autoboxing

    Autoboxing eliminates the drudgery of manual conversionbetween primitive types (such as int) and wrapper types (such

    as Integer).

    Any primitive variable can accept an instance whose type is the

    corresponding primitive wrapper.

    Any primitive wrapper reference variable can accept thecorresponding primitive value as a value;

    Float f = 9.9f;

    in ti = newInteger(99);

    ** Refer to the AutoboxingSample.java sample code

  • 8/10/2019 M14 - Advanced Language Features

    11/24

    11

    Variable Arguments (Varargs)

    Variable arguments allow methods to take in multiple argumentsof the same type without specifying the number of argumentsduring runtime.

    publ icvoid listNames(Stringnames){

    fo r(String i : names) {

    System.out.println(i);}

    }

    The method will be able to accept a series of Strings as aparameters that will be converted into an array.

    If there are other arguments in the method, the others cannot bevarargs and the vararg must be the last parameter in the list.

    ** Refer to the VarArgsSample.java sample code

  • 8/10/2019 M14 - Advanced Language Features

    12/24

    12

    An enum typeis a type whose fieldsconsist of a fixed set ofconstants.

    The most simple use is to list a series of constants and

    contained by an enum type.

    See EnumBasic.java and Seasons.java for sample enums code.

    enum Seasons{

    SPRING, SUMMER, FALL, WINTER

    }

    fo r(Seasons s : Seasons.values()){

    System.out.println(s);

    }

    Typesafe Enums

  • 8/10/2019 M14 - Advanced Language Features

    13/24

  • 8/10/2019 M14 - Advanced Language Features

    14/24

    14

    Static Imports

    A static importdeclaration enables programmers to refer toimported static members as if they were declared in the class

    that uses them.

    A static import declaration has two forms:

    Single static import - imports a particular static member.

    Static import on demandimports all static members of a class.

    ** Refer to the StaticImportSample.java sample code

  • 8/10/2019 M14 - Advanced Language Features

    15/24

    15

    Annotations

    Annotations provide data about a program that is not part of theprogram itself.

    Annotations can be used to pass information to the compiler

    about the source code.

    Various software tools can use annotations to generate

    additional information, resources, or code based on theannotation.

  • 8/10/2019 M14 - Advanced Language Features

    16/24

    16

    Annotations Syntax

    Annotations are marked by the @ symbol and by conventionbelong in their own line.@Override

    Annotations can be given a single value.

    @SuppressWarnings("unchecked")

    @SuppressWarnings(value = "unchecked")

    Annotations can be given multiple named-value pairs.

    @Author(

    name = John Doe",

    date = 7/23/2008"

    )

  • 8/10/2019 M14 - Advanced Language Features

    17/24

    17

    Compiler Annotations

    @Override Indicates that the annotated method is required to override a method

    from its parent class.

    The compiler will generate errors when the superclass method being

    annotated is not overridden.

    @Deprecated Marks a certain target element, like a method, as deprecated or

    outdated.

    The compiler will generate warnings when source code that calls

    deprecated methods is compiled.

    @SuppressWarnings

    Used to tell the compiler to ignore warnings like deprecation.

  • 8/10/2019 M14 - Advanced Language Features

    18/24

    18

    Defining Annotations

    Custom annotations are similar to declaring a class/interfacesource.

    Custom annotations are defined by using the @ symbol

    followed by the interface keyword.

    These can be accessed by the source code using imports just

    like any other class or interface.

  • 8/10/2019 M14 - Advanced Language Features

    19/24

    19

    Defining Annotations (cont.)

    Many annotations have no elements except the annotationname itself.

    public @interface MyAnnotation{}

    Single element annotation possess a single element.

    public @interface MyAnnotation{

    String myStringValue();

    }

    Multi-value annotations can have multiple elements.public @interface MyAnnotation{

    String myStringValue();

    int myIntValue();

    }

  • 8/10/2019 M14 - Advanced Language Features

    20/24

    20

    Defining Annotations (cont.)

    Method declarations should not have any parameters. Method declarations should not have any throws clauses.

    Return types are limited to the following:

    Primitives

    String

    Class

    Enum

    Array of the above types

  • 8/10/2019 M14 - Advanced Language Features

    21/24

    21

    Defining Annotations (cont.)

    @TargetDefines what elements an annotation can be applied to:

    @Target(ElementType.TYPE)can be applied to a class or interface

    @Target(ElementType.FIELD)can be applied to a field or property

    @Target(ElementType.METHOD)can be applied to a method levelannotation

    @Target(ElementType.PARAMETER)can be applied to the parameters of

    a method @Target(ElementType.CONSTRUCTOR)can be applied to constructors

    @Target(ElementType.LOCAL_VARIABLE)can be applied to localvariables

    @Target(ElementType.ANNOTATION_TYPE)indicates that the declaredtype itself is an annotation type

    @RetentionDefines how long an annotation is maintained RetentionPolicy.SOURCE: source level and will be ignored by the compiler

    RetentionPolicy.CLASS: retained by the compiler at compile time, butignored by the VM

    RetentionPolicy.RUNTIME: retained by the VM so they can be read only atrun-time

  • 8/10/2019 M14 - Advanced Language Features

    22/24

    22

    Defining Annotations (cont.)

    @DocumentedAnnotations of this type will be documented bythe javadoc tool.

    @InheritedClasses annotated with this type of annotation will

    be automatically inherited.

    ** Refer to the Task.java and AnnotationsSample.java sample code

  • 8/10/2019 M14 - Advanced Language Features

    23/24

  • 8/10/2019 M14 - Advanced Language Features

    24/24

    24

    Activity

    1) Browse to sef.module15.activity.2) Complete the implementation of

    PermissionList based on the

    requirements of the interface

    Permissable and the enumerated

    values in Permission.3) Use PermissionTest to verify your

    implementation.


Recommended