java-session07-12651098

436 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
436
On SlideShare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
13
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

java-session07-12651098

  1. 1. Java Programming LanguageObjectives 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 Ver. 1.0 Session 7 Slide 1 of 24
  2. 2. Java Programming LanguageThe 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. Ver. 1.0 Session 7 Slide 2 of 24
  3. 3. Java Programming LanguageBlank 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. Ver. 1.0 Session 7 Slide 3 of 24
  4. 4. Java Programming LanguageEnumerated 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. Ver. 1.0 Session 7 Slide 4 of 24
  5. 5. Java Programming LanguageStatic 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); Ver. 1.0 Session 7 Slide 5 of 24
  6. 6. Java Programming LanguageAbstract 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 Ver. 1.0 Session 7 Slide 6 of 24
  7. 7. Java Programming LanguageAbstract 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. Ver. 1.0 Session 7 Slide 7 of 24
  8. 8. Java Programming LanguageAbstract 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. Ver. 1.0 Session 7 Slide 8 of 24
  9. 9. Java Programming LanguageInterfaces 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>* } Ver. 1.0 Session 7 Slide 9 of 24
  10. 10. Java Programming LanguageInterfaces (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. Ver. 1.0 Session 7 Slide 10 of 24
  11. 11. Java Programming LanguageInterfaces (Contd.) 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 Ver. 1.0 Session 7 Slide 11 of 24
  12. 12. Java Programming LanguageExceptions 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 Ver. 1.0 Session 7 Slide 12 of 24
  13. 13. Java Programming LanguageExceptions 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. Ver. 1.0 Session 7 Slide 13 of 24
  14. 14. Java Programming LanguageExceptions (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>) Ver. 1.0 Session 7 Slide 14 of 24
  15. 15. Java Programming LanguageThe 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. Ver. 1.0 Session 7 Slide 15 of 24
  16. 16. Java Programming LanguageThe 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); } Ver. 1.0 Session 7 Slide 16 of 24
  17. 17. Java Programming LanguageCall 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. Ver. 1.0 Session 7 Slide 17 of 24
  18. 18. Java Programming LanguageThe 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. Ver. 1.0 Session 7 Slide 18 of 24
  19. 19. Java Programming LanguageCreating 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. Ver. 1.0 Session 7 Slide 19 of 24
  20. 20. Java Programming LanguageDemonstration Let see how to create a custom Exception class, and use it in a Java program. Ver. 1.0 Session 7 Slide 20 of 24
  21. 21. Java Programming LanguageAssertions 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. Ver. 1.0 Session 7 Slide 21 of 24
  22. 22. Java Programming LanguageAssertions (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. Ver. 1.0 Session 7 Slide 22 of 24
  23. 23. Java Programming LanguageSummary 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. Ver. 1.0 Session 7 Slide 23 of 24
  24. 24. Java Programming LanguageSummary (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 Ver. 1.0 Session 7 Slide 24 of 24

×