java session07

Upload: praveenkumar7457

Post on 29-May-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 JAVA Session07

    1/24

    Slide 1 of 24Session 7Ver. 1.0

    Java Programming Language

    In this session, you will learn to:

    Create final classes, methods, and variables

    Create and use enumerated types

    Use the static import statement

    Create abstract classes and methods

    Create and use an interface

    Define exceptions

    Use try, catch, and finally statements

    Describe exception categories

    Identify common exceptionsDevelop programs to handle your own exceptions

    Use assertions

    Distinguish appropriate and inappropriate uses of assertions

    Enable assertions at runtime

    Objectives

  • 8/8/2019 JAVA Session07

    2/24

    Slide 2 of 24Session 7Ver. 1.0

    Java Programming Language

    The final Keyword

    The final keyword is used for security reasons.

    It is used to create classes that serve as a standard.

    It implements the following restrictions:

    You cannot subclass a final class.

    You cannot override a final method.

    A final variable is a constant.

    All methods and data members in a final class are implicitly

    final.

    You can set a final variable once only, but that

    assignment can occur independently of the declaration;this is called a blank final variable.

  • 8/8/2019 JAVA Session07

    3/24

    Slide 3 of 24Session 7Ver. 1.0

    Java Programming Language

    Blank Final Variables

    A final variable that is not initialized in its declaration; its

    initialization is delayed:

    A blank final instance variable must be assigned in a

    constructor.

    A blank final local variable can be set at any time in the body ofthe method.

    It can be set once only.

  • 8/8/2019 JAVA Session07

    4/24

    Slide 4 of 24Session 7Ver. 1.0

    Java Programming Language

    Enumerated Types

    An enum type field consist of a fixed set of constants.

    You can define an enum type by using the enum keyword.

    For example, you would specify a days-of-the-week enum

    type as:

    public enum Day { SUNDAY, MONDAY, TUESDAY,WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

    The enum class body can include methods and other fields.

    The compiler automatically adds some special methodswhen it creates an enum.

    All enums implicitly extend from java.lang.Enum. SinceJava does not support multiple inheritance, an enum cannotextend anything else.

  • 8/8/2019 JAVA Session07

    5/24

    Slide 5 of 24Session 7Ver. 1.0

    Java Programming Language

    Static Imports

    Imports the static members from a class:

    import static..;

    OR

    import static ..*;

    Imports members individually or collectively:

    import static cards.domain.Suit.SPADES;

    OR

    import static cards.domain.Suit.*;There is no need to qualify the static constants:

    PlayingCard card1 = new PlayingCard(SPADES,2);

  • 8/8/2019 JAVA Session07

    6/24

    Slide 6 of 24Session 7Ver. 1.0

    Java Programming Language

    Abstract Classes

    An abstract class is declared with abstract access

    specifier and it may or may not include abstract methods.

    Abstract classes cannot be instantiated, but they can be

    subclassed. For example:

    Shape

    Circle Rectangle Hexagon

  • 8/8/2019 JAVA Session07

    7/24

    Slide 7 of 24Session 7Ver. 1.0

    Java Programming Language

    Abstract Classes (Contd.)

    An abstract class defines the common properties and

    behaviors of other classes.

    It is used as a base class to derive specific classes of the

    same type. For example:

    abstract class Shape

    {

    public abstract float calculateArea();

    }

    The preceding abstract method, calculateArea, is inherited

    by the subclasses of the Shape class. The subclasses

    Rectangle, Circle, and Hexagon implement this method in

    different ways.

  • 8/8/2019 JAVA Session07

    8/24

    Slide 8 of 24Session 7Ver. 1.0

    Java Programming Language

    Abstract Classes (Contd.)

    A simple example of implementation of Abstract Method:

    public class Circleextends Shape

    {

    float radius;

    public float calculateArea()

    {

    return ((radius * radius)* (22/7));

    }

    }In the preceding example, the calculateArea() method has

    been overridden in the Circle class.

  • 8/8/2019 JAVA Session07

    9/24

    Slide 9 of 24Session 7Ver. 1.0

    Java Programming Language

    Interfaces

    A public interface is a contract between client code and the

    class that implements that interface.

    A Java interface is a formal declaration of such a contract in

    which all methods contain no implementation.

    Many unrelated classes can implement the same interface.

    A class can implement many unrelated interfaces.

    Syntax of a Java class declaration with interface

    implementation is as follows:

    class [extends

    ]

    [implements [,]* ]

    { *

    }

  • 8/8/2019 JAVA Session07

    10/24

    Slide 10 of 24Session 7Ver. 1.0

    Java Programming Language

    Interfaces (Contd.)

    Interfaces are used to define a behavior protocol (standard

    behavior) that can be implemented by any class anywhere

    in the class hierarchy. For example:

    Consider the devices TV and VDU. Both of them require a

    common functionality as far as brightness control isconcerned. This functionality can be provided by

    implementing an interface called BrightnessControl which is

    applicable for both the devices.

    Interfaces can be implemented by classes that are not

    related to one another.Abstract classes are used only when there is a kind-of

    relationship between the classes.

  • 8/8/2019 JAVA Session07

    11/24

    Slide 11 of 24Session 7Ver. 1.0

    Java Programming Language

    Uses of Interfaces:

    Declaring methods that one or more classes are expected to

    implement

    Determining an objects programming interface without

    revealing the actual body of the classCapturing similarities between unrelated classes without

    forcing a class relationship

    Simulating multiple inheritance by declaring a class that

    implements several interfaces

    Interfaces (Contd.)

  • 8/8/2019 JAVA Session07

    12/24

    Slide 12 of 24Session 7Ver. 1.0

    Java Programming Language

    Exceptions and Assertions

    Exceptions are a mechanism used to describe what to do

    when something unexpected happens. For example:

    When a method is invoked with unacceptable arguments

    A network connection fails

    The user asks to open a non-existent file

    Assertions are a way to test certain assumptions about the

    logic of a program. For example:

    To test that the value of a variable at a particular point is

    always positive

  • 8/8/2019 JAVA Session07

    13/24

    Slide 13 of 24Session 7Ver. 1.0

    Java Programming Language

    Exceptions

    Conditions that can readily occur in a correct program are

    checked exceptions.

    These are represented by the Exception class.

    Severe problems that normally are treated as fatal or

    situations that probably reflect program bugs are uncheckedexceptions.

    Fatal situations are represented by the Error class.

    Probable bugs are represented by the RuntimeException

    class.

    The API documentation shows checked exceptions that canbe thrown from a method.

  • 8/8/2019 JAVA Session07

    14/24

    Slide 14 of 24Session 7Ver. 1.0

    Java Programming Language

    Exceptions (Contd.)

    Consider the following code snippet:

    public void myMethod(int num1 , int num2)

    {

    int result;

    result = num2 / num1;System.out.println(Result: + result);

    }

    In the preceding piece of code an exceptionjava.lang.ArithmeticException is thrown when the

    value of num1 is equal to zero.T

    he error messagedisplayed is:

    Exception in thread mainjava.lang.ArithmeticException: / by zero at.main()

  • 8/8/2019 JAVA Session07

    15/24

    Slide 15 of 24Session 7Ver. 1.0

    Java Programming Language

    The try-catch Statement

    The try-catch block:

    The try block governs the statements that are enclosed within

    it and defines the scope of the exception-handlers associated

    with it.

    A try block must have at least one catch block that follows itimmediately.

    The catch statement takes the object of the exception class

    that refers to the exception caught, as a parameter.

    Once the exception is caught, the statements within the catch

    block are executed.

    The scope of the catch block is restricted to the statements inthe preceding try block only.

  • 8/8/2019 JAVA Session07

    16/24

    Slide 16 of 24Session 7Ver. 1.0

    Java Programming Language

    The try-catch Statement (Contd.)

    An example of try-catch block:public void myMethod(int num1 , int num2){int result;try{result = num2 / num1;

    }catch(ArithmeticException e){System.out.println(Errordivision byzero);

    }System.out.println(Result: + result);

    }

  • 8/8/2019 JAVA Session07

    17/24

    Slide 17 of 24Session 7Ver. 1.0

    Java Programming Language

    Call Stack Mechanism

    If an exception is not handled in the current try-catch block,

    it is thrown to the caller of the method.

    If the exception gets back to the main method and is not

    handled there, the program is terminated abnormally.

  • 8/8/2019 JAVA Session07

    18/24

    Slide 18 of 24Session 7Ver. 1.0

    Java Programming Language

    The finally Clause

    The characteristics of the finally clause:

    Defines a block of code that always executes, regardless of

    whether an exception is thrown.

    The finally block follows the catch blocks.

    It is not mandatory to have a finally block.

  • 8/8/2019 JAVA Session07

    19/24

    Slide 19 of 24Session 7Ver. 1.0

    Java Programming Language

    Creating Your Own Exceptions

    Characteristics of user-defined exceptions:

    Created by extending the Exception class.

    The extended class contains constructors, data members and

    methods.

    The throw and throws keywords are used whileimplementing user-defined exceptions.

  • 8/8/2019 JAVA Session07

    20/24

    Slide 20 of 24Session 7Ver. 1.0

    Java Programming Language

    Let see how to create a custom Exception class, and use it in a

    Java program.

    Demonstration

  • 8/8/2019 JAVA Session07

    21/24

    Slide 21 of 24Session 7Ver. 1.0

    Java Programming Language

    Syntax of an assertion is:

    assert ;

    assert : ;

    If evaluates false, then anAssertionError is thrown.

    The second argument is converted to a string and used asdescriptive text in the AssertionError message.

    Assertions

  • 8/8/2019 JAVA Session07

    22/24

    Slide 22 of 24Session 7Ver. 1.0

    Java Programming Language

    Assertions (Contd.)

    Recommended Uses of Assertions:

    Use assertions to document and verify the assumptions and

    internal logic of a single method:

    Internal invariants

    Control flow invariantsPostconditions and class invariants

    Inappropriate Uses of Assertions:

    Do not use assertions to check the parameters of a public

    method.

    Do not use methods in the assertion check that can cause

    side-effects.

  • 8/8/2019 JAVA Session07

    23/24

    Slide 23 of 24Session 7Ver. 1.0

    Java Programming Language

    Summary

    In this session, you learned that:

    final classes cannot be subclassed,final methods cannot

    be overriden, and final variables are constant.

    An enum type is a type whose fields consist of a fixed set of

    constants.An abstract class defines the common properties and

    behaviors of other classes. It is used as a base class to derive

    specific classes of the same type:

    Abstract classes allow implementation of a behavior in different

    ways. The implementation is done in subclasses.

    An abstract class cannot be instantiated.Subclasses must override the abstract methods of the super

    class.

    Interfaces are used to define a behavior protocol that can be

    implemented by any class anywhere in the class hierarchy.

  • 8/8/2019 JAVA Session07

    24/24

    Slide 24 of 24Session 7Ver. 1.0

    Java Programming Language

    Summary (Contd.)

    An exception is an abnormal event that occurs during the

    program execution and disrupts the normal flow of instructions.

    You can implement exception handling in your program by

    using the following keywords:

    try

    catch

    throws/throw

    finally

    Assertions can be used to document and verify the

    assumptions and internal logic of a single method:

    Internal invariantsControl flow invariants

    Postconditions and class invariants