java-session07-12651098

24
Slide 1 of 24 Session 7 Ver. 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 exceptions Develop programs to handle your own exceptions Use assertions Distinguish appropriate and inappropriate uses of assertions Enable assertions at runtime Objectives

Transcript of java-session07-12651098

Page 1: java-session07-12651098

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 exceptions

Develop programs to handle your own exceptions

Use assertions

Distinguish appropriate and inappropriate uses of assertions

Enable assertions at runtime

Objectives

Page 2: java-session07-12651098

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.

Page 3: java-session07-12651098

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 of the method.

It can be set once only.

Page 4: java-session07-12651098

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 methods when it creates an enum.

All enums implicitly extend from java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.

Page 5: java-session07-12651098

Slide 5 of 24Session 7Ver. 1.0

Java Programming Language

Static Imports

Imports the static members from a class:

import static <pkg_list>.<class_name>.<member_name>;

OR

import static <pkg_list>.<class_name>.*;

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);

Page 6: java-session07-12651098

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

Page 7: java-session07-12651098

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.

Page 8: java-session07-12651098

Slide 8 of 24Session 7Ver. 1.0

Java Programming Language

Abstract Classes (Contd.)

A simple example of implementation of Abstract Method:

public class Circle extends 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.

Page 9: java-session07-12651098

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:

<modifier> class <name> [extends <superclass>]

[implements <interface> [,<interface>]* ]

{ <member_declaration>*

}

Page 10: java-session07-12651098

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 is concerned. 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.

Page 11: java-session07-12651098

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 object’s programming interface without revealing the actual body of the class

Capturing similarities between unrelated classes without forcing a class relationship

Simulating multiple inheritance by declaring a class that implements several interfaces

Interfaces (Contd.)

Page 12: java-session07-12651098

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

Page 13: java-session07-12651098

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 unchecked exceptions.

Fatal situations are represented by the Error class.

Probable bugs are represented by the RuntimeException class.

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

Page 14: java-session07-12651098

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 exception java.lang.ArithmeticException is thrown when the value of num1 is equal to zero. The error message displayed is:Exception in thread “main” java.lang.ArithmeticException: / by zero at <classname>.main(<filename>)

Page 15: java-session07-12651098

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 it immediately.

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 in the preceding try block only.

Page 16: java-session07-12651098

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(“Error…division by zero”);

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

}

Page 17: java-session07-12651098

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.

Page 18: java-session07-12651098

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.

Page 19: java-session07-12651098

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 while implementing user-defined exceptions.

Page 20: java-session07-12651098

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

Page 21: java-session07-12651098

Slide 21 of 24Session 7Ver. 1.0

Java Programming Language

Syntax of an assertion is:

assert <boolean_expression> ;

assert <boolean_expression> : <detail_expression> ;

If <boolean_expression> evaluates false, then an AssertionError is thrown.

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

Assertions

Page 22: java-session07-12651098

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 invariants

Postconditions 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.

Page 23: java-session07-12651098

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.

Page 24: java-session07-12651098

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 invariants

Control flow invariants

Postconditions and class invariants