Md06 advance class features


Published on

  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Md06 advance class features

  1. 1. <ul><ul><li>Module 6 </li></ul></ul><ul><ul><li> Advanced Class Features </li></ul></ul><ul><li>  </li></ul>
  2. 2. <ul><li>Objectives </li></ul><ul><ul><li>• Define overloading, overriding. </li></ul></ul><ul><ul><li>• Describe constructor and method overloading </li></ul></ul><ul><ul><li>• In a Java program, identify the following: Overloaded methods and constructors The use of this to call overloaded constructors </li></ul></ul><ul><ul><li>Overridden methods </li></ul></ul><ul><ul><li>The use of super to call parent class methods </li></ul></ul><ul><ul><li>• Using static import statement </li></ul></ul>
  3. 3. <ul><li>Objectives </li></ul><ul><ul><li>• Java Enumerations </li></ul></ul><ul><ul><li>• Wrapper Classes and Use </li></ul></ul><ul><ul><li>• AutoBoxing/Unboxing </li></ul></ul><ul><ul><li>• Annotations(Metadata) </li></ul></ul><ul><ul><li>• Describe Inner Classes </li></ul></ul>
  4. 4. <ul><ul><li>Overloading Methods </li></ul></ul><ul><ul><li>When two or more methods within the same class share </li></ul></ul><ul><ul><li>the same name, as long as their parameter declarations </li></ul></ul><ul><ul><li>are different,the methods are said to be overloaded, </li></ul></ul><ul><ul><li>and the process is referred to as method overloading. </li></ul></ul><ul><ul><li>Method overloading is one of the ways that Java </li></ul></ul><ul><ul><li>implements polymorphism. </li></ul></ul><ul><ul><li>Overloaded methods must differ in the type and/or </li></ul></ul><ul><ul><li>number of their parameters. </li></ul></ul><ul><li>Example </li></ul>
  5. 5. Note Which over loaded version of the method to call is based on the reference type of the argument passed at compile time. Example
  6. 6. <ul><li>Constructors </li></ul><ul><li>Every class, including abstract classes , MUST have a constructor. </li></ul><ul><ul><li>A constructor looks like this: </li></ul></ul><ul><ul><li>class Foo { </li></ul></ul><ul><ul><li>Foo() { } // The constructor for the Foo class </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>Constructors donot have any return type and their name must </li></ul><ul><li>exactly match the class name. </li></ul>
  7. 7. Constructors are used to initialize instance variable state. class Foo { int size; String name; Foo(String name, int size) { = name; this.size = size; } }
  8. 8. <ul><li>Rules for Constructors </li></ul><ul><ul><li>• Constructors can use any access modifier, including private. </li></ul></ul><ul><ul><li>• The constructor name must match the name of the class. </li></ul></ul><ul><ul><li>• Constructors must not have a return type. </li></ul></ul><ul><ul><li>• It's legal (but stupid) to have a method with the same name as </li></ul></ul><ul><ul><li>the class, but that doesn't make it a constructor. If you see a </li></ul></ul><ul><ul><li>return type, it's a method rather than a constructor. </li></ul></ul><ul><ul><li>• If you don't type a constructor into your class code, a default </li></ul></ul><ul><ul><li>constructor will be automatically generated by the compiler. </li></ul></ul>
  9. 9. <ul><ul><li>• If you want a no-arg constructor and you've typed any other </li></ul></ul><ul><ul><li>constructor(s) into your class code, the compiler won't provide </li></ul></ul><ul><ul><li>the no-arg constructor </li></ul></ul><ul><ul><li>• Interfaces do not have constructors. Interfaces are not part of an </li></ul></ul><ul><ul><li>object's inheritance tree. </li></ul></ul><ul><ul><li>• The first line in a constructor must be a call to super() or a call </li></ul></ul><ul><ul><li>to this(). </li></ul></ul><ul><li>Example </li></ul>
  10. 10. Method Overriding When a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. The rules for overriding a method are as follows: • The argument list must exactly match that of the overridden method. If they don't match, you can end up with an overloaded method • The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass. • The access level can't be more restrictive than the overridden method's.
  11. 11. • The access level CAN be less restrictive than that of the overridden method. • The overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception. • The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. • You cannot override a method marked final. • You cannot override a method marked static. • If a method can't be inherited, you cannot override it.
  12. 12. Examples Legal and Illegal method overrides Consider public class Animal{ public void eat(){ } }
  13. 13. <ul><li>Example </li></ul><ul><li>Consider this example </li></ul><ul><ul><li>public class Animal { </li></ul></ul><ul><ul><ul><li>public void eat() { </li></ul></ul></ul><ul><ul><ul><li>System.out.println(&quot;Generic Animal Eating Generically&quot;); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>public class Horse extends Animal { </li></ul></ul><ul><ul><ul><li>public void eat() { </li></ul></ul></ul><ul><ul><ul><li>System.out.println(&quot;Horse eating hay &quot;); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>public void eat(String s) { </li></ul></ul></ul><ul><ul><ul><li>System.out.println(&quot;Horse eating &quot; + s); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>Horse class has both overloaded and overridden the eat() method. </li></ul></ul>
  14. 16. Note Which over ridden version of the method to call is decided at runtime based on object type. Why Overridden Methods? Overridden methods allow Java to support run-time polymorphism. A call to an overridden method is resolved at run time, rather than compile time. Example
  15. 17. Difference between Overloaded and Overridden methods
  16. 18. The Super Keyword super is used in a class to refer to its superclass super is used to refer to the members of superclass, both data attributes and methods Behavior invoked does not have to be in the superclass; it can be further up in the hierarchy
  17. 19. Example interface I { int x = 0; } class T1 implements I { int x = 1; } class T2 extends T1 { int x = 2; } class T3 extends T2 { int x = 3; void test() { System.out.println(&quot;x=tt&quot;+x); System.out.println(&quot;super.x=tt&quot;+super.x); System.out.println(&quot;((T2)this).x=t&quot;+((T2)this).x); System.out.println(&quot;((T1)this).x=t&quot;+((T1)this).x); System.out.println(&quot;((I)this).x=t&quot;+((I)this).x); } } class Test { public static void main(String[] args) { new T3().test(); } }
  18. 20. Static import Statement This statement is used in situations where there is a need of frequent access to static final fields (constants) and static methods from one or two classes. Prefixing the name of these classes over and over can result in cluttered code. The static import statement gives a way to import the constants and static methods so as to avoid to prefix the name of their class.
  19. 21. The java.lang.Math class defines the PI constant and many static methods, including methods for calculating sines, cosines, tangents, square roots, maxima, minima, exponents, and many more. For example, public static final double PI 3.141592653589793 public static double cos(double a) Ordinarily, to use these objects from another class, you prefix the class name, as follows. double r = Math.cos(Math.PI * 2);
  20. 22. Use the static import statement to import the static members of java.lang.Math so that you don't need to prefix the class name, Math. The static members of Math can be imported either individually: import static java.lang.Math.PI; or as a group: import static java.lang.Math.*; Once they have been imported, the static members can be used without qualification double r = cos(PI * 2);
  21. 23. Enumerations With JDK 5.0 , Java restrict a variable to having one of only a few predefined values – in other words, one value from enumerated list By using this simple declaration enum CoffeeSize { BIG, HUGE, OVERWHELMING} you can guarantee that the compiler will stop you from assigning anything to coffeeSize except BIG, HUGE, OVERWHELMING. Statement like this CoffeeSize cs = CoffeeSize.LARGE; will give compile time error.
  22. 24. Enumerations • It’s a list of named constants. • Enumerations were added to Java language beginning with JDK 5.0 • In Java enumeration defines a class type. • An enumeration is created using enum keyword enum Apple{ Jonathan, GoldenDel, RedDel, Winesap, Cortland } Here enumeration list various Apple varieties. Example EnumDemo
  23. 25. <ul><li>• The identifiers Jonathan,GoldenDel and so on are called </li></ul><ul><li>enumeration constants. </li></ul><ul><li>• Each is implicitly declared as public,static final member of Apple. </li></ul><ul><li>• Once enumeration is defined ,a variable of that type can be created. </li></ul><ul><li>• Even though enumeration define a class type,its not instantiated </li></ul><ul><li>using new. </li></ul><ul><ul><li>• Apple ap, declares ap as variable of enumeration type. </li></ul></ul><ul><ul><li>• Since ap is of type Apple, the only value that it can be assigned </li></ul></ul><ul><ul><li>are those defined by enumeration. </li></ul></ul><ul><ul><li>ap=Apple.RedDel; //assign ap the value RedDel. </li></ul></ul>
  24. 26. <ul><ul><li>• Two enumeration constants can be compared for equality by </li></ul></ul><ul><ul><li>using == operator. </li></ul></ul><ul><ul><li>if (ap==Apple.GoldenDel) </li></ul></ul><ul><li>• An enumeration value can be used to control a switch statement </li></ul><ul><ul><li>switch(ap){ </li></ul></ul><ul><ul><li>case Jonathan: </li></ul></ul><ul><ul><li>//…… </li></ul></ul><ul><ul><li>case Winesap: </li></ul></ul><ul><ul><li>//……. </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>• When an enumeration constant is displayed such as in println() </li></ul><ul><li>statement,its name is output </li></ul><ul><li>System.out.println(Apple.Winesap); </li></ul><ul><li>The name Winesap is displayed. </li></ul>
  25. 27. Enums Declaration Outside class Example Inside class Example What would be the output public class CoffeeTest1 { public static void main(String[] args) { enum CoffeeSize { BIG, HUGE, OVERWHELMING } Coffee drink = new Coffee(); drink.size = CoffeeSize.BIG; } }
  26. 28. Answer Compile time error, cannot declare enums in method. Note • Semicolon at the end of enum declaration is optional. • enums are not Strings or ints, each of the enumerated CoffeeSize types are actually instance of CoffeeSize.
  27. 29. enum is a kind of class which look something like this class CoffeeSize { public static final CoffeeSize BIG =new CoffeeSize(&quot;BIG&quot;, 0); public static final CoffeeSize HUGE =new CoffeeSize(&quot;HUGE&quot;, 1); public static final CoffeeSize OVERWHELMING = new CoffeeSize(&quot;OVERWHELMING&quot;, 2); public CoffeeSize(String enumName, int index) { // stuff here } public static void main(String[] args) { System.out.println(CoffeeSize.BIG); } }
  28. 30. <ul><li>Declaring Constructors, Methods and Variables in an enum </li></ul><ul><li>Example </li></ul><ul><li>Remember </li></ul><ul><li>You can NEVER invoke an enum constructor directly. </li></ul><ul><ul><li>The enum constructor is invoked automatically, with the </li></ul></ul><ul><ul><li>arguments you define after the constant value. </li></ul></ul><ul><ul><li>You can define more than one argument to the constructor, and </li></ul></ul><ul><ul><li>you can overload the enum constructors, just as you can overload </li></ul></ul><ul><ul><li>a normal class constructor. </li></ul></ul>
  29. 31. values() and valueOf() Methods • All enumerations automatically contain two predefined methods values() and valueOf() • The values() method returns an array that contains a list of enumeration constants. • valueOf() method returns the enumeration constant whose value correspond to the string passed in str. Example EnumDemo2
  30. 32. Java Enumerations are Class Types Although its not possible to instantiate an enum using new,but it has the same capabilities as other classes. Each enumeration constant is an object of its enumeration type.So if a constructor is defined for an enum,the constructor is called when each enumeration constant is created. Example EnumDemo3
  31. 33. Enumerations Inherit Enum Its not possible to inherit a superclass when declaring an enum, All enumerations automatically inherit one: java.lang.Enum Three commonly used methods of Enum class final int ordial() This is used to obtain a value that indicates an enumeration constant’s position in the list of constants. final int compareTo(enum-type e) Used to compare the ordinal value of two constants. equals() To compare for equality of an enumeration constant with any other object.
  32. 34. Wrapper Classes Java use the simple data type such as int or char,these data types are not part of object hierarchy. At times its needed to create an object representation for one of these simple types. For example Data structures implemented by Java operate on objects which means these cannot be used to store primitive types.
  33. 35. Wrapper Classes and their Constructor Arguments
  34. 36. <ul><li>The Wrapper Constructors </li></ul><ul><li>All of the wrapper classes except Character provide two </li></ul><ul><li>constructors: </li></ul><ul><li>one that takes a primitive of the type being constructed, </li></ul><ul><li>and one that takes a String representation of the type being constructed. </li></ul><ul><ul><li>Integer i1 = new Integer(42); </li></ul></ul><ul><ul><li>Integer i2 = new Integer(&quot;42&quot;); </li></ul></ul><ul><li>The Character class provides only one constructor, which takes a </li></ul><ul><li>char as an argument </li></ul><ul><li>Character c1 = new Character('c'); </li></ul>
  35. 37. valueOf() Provide an approach to creating wrapper objects. Float f2 = Float.valueOf(&quot;3.14f&quot;); // assigns 3.14 to the Float object f2 xxxValue() When you need to convert the value of a wrapped numeric to a primitive, use one of the many xxxValue() methods. Integer i2 = new Integer(42); byte b = i2.byteValue(); short s = i2.shortValue();
  36. 38. parseXxx() Both parseXxx() and valueOf() take a String as an argument. The difference between the two methods is • parseXxx() returns the named primitive. • valueOf() returns a newly created wrapped object of the type that invoked the method. double d4 = Double.parseDouble(&quot;3.14&quot;); // convert a String to a primitive result is d4 = 3.14 toString() toString() method allow you to get some meaningful representation of a given object. Double d = new Double(&quot;3.14&quot;); System.out.println(&quot;d = &quot;+ d.toString() );
  37. 39. In summary, the essential method signatures for Wrapper conversion methods are primitive xxxValue() - to convert a Wrapper to a primitive primitive parseXxx(String) - to convert a String to a primitive Wrapper valueOf(String) - to convert a String to a Wrapper
  38. 40. Boxing The process of encapsulating a value within an object is called boxing. Integer iOb= new Integer(100); Unboxing The process of extracting avalue from a type wrapper is called unboxing. int i = iOb.intValue();
  39. 41. Autoboxing/unboxing With JDK 5, Java added two important features: autoboxing and auto-unboxing. Autoboxing is a process by which a primitive type is automatically encapsulated into its equivalent type wrapper whenever the object of that type is needed. Auto-unboxing is a process by which the value of a boxed object is automatically extracted from a type wrapper when its value is needed. There is no need to call a method as intValue() or doubleValue().
  40. 42. The modern way to construct an Integer object that has the value 100 Integer iOb=100; To unbox an object, assign that object reference to a primitive type variable int i=iOb; Example Autoboxing with method parameters and return values Example
  41. 43. <ul><ul><li>Auto-unboxing also allows to mix different types of numeric </li></ul></ul><ul><ul><li>objects in an expression. </li></ul></ul><ul><ul><ul><li>Integer iOb=100; </li></ul></ul></ul><ul><ul><ul><li>Double dOb=98.6; </li></ul></ul></ul><ul><ul><ul><li>dOb=dOb+iOb; </li></ul></ul></ul><ul><ul><li>Autoboxing/unboxing can also prevent errors. </li></ul></ul><ul><ul><ul><li>Integer iOb=1000; </li></ul></ul></ul><ul><ul><ul><li>int i=iOb.byteValue(); </li></ul></ul></ul><ul><ul><ul><li>System.out.println(i); </li></ul></ul></ul>
  42. 44. <ul><li>What would be the output in the following case </li></ul><ul><li>Integer i3 = 10; </li></ul><ul><li>Integer i4 = 10; </li></ul><ul><li>if(i3 == i4) System.out.println(&quot;same object&quot;); </li></ul><ul><li>if(i3.equals(i4)) System.out.println(&quot;meaningfully equal&quot;); </li></ul><ul><li>Two instances of the following wrapper objects will always be == </li></ul><ul><li>when their primitive values are the same: </li></ul><ul><ul><li>Boolean </li></ul></ul><ul><ul><li>Byte </li></ul></ul><ul><ul><li>Character from u0000 to u007f (7f is 127 in decimal) </li></ul></ul><ul><ul><li>Short and Integer from -128 to 127 </li></ul></ul><ul><li>This example produces the output: </li></ul><ul><ul><li>same object </li></ul></ul><ul><ul><li>meaningfully equal </li></ul></ul>
  43. 45. Overloading with Boxing class AddBoxing { static void go(Integer x) { System.out.println(&quot;Integer&quot;); } static void go(long x) { System.out.println(&quot;long&quot;); } public static void main(String [] args) { int i = 5; go(i); // which go() will be invoked? } } The answer is that the compiler will choose widening over boxing, so the output will be long
  44. 46. <ul><li>The Object Class </li></ul><ul><ul><li>• The Object class is the root of all classes in Java </li></ul></ul><ul><ul><li>• A class declaration with no extends clause, implicitly </li></ul></ul><ul><ul><li>uses &quot;extends Object&quot; </li></ul></ul><ul><ul><ul><ul><ul><li>public class Employee { ... } </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>is equivalent to: </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>public class Employee extends Object{ </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>... </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul></ul>
  45. 47. Methods of Object class
  46. 48. Nested and Inner Class It is possible to define a class within another class; such classes are known as nested classes . The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A, then B is known to A, but not outside of A. A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class.
  47. 49. <ul><ul><li>Other, access specifiers you may use are </li></ul></ul><ul><ul><li>private, public, and protected </li></ul></ul><ul><li>There are two types of nested classes: static and non-static . </li></ul>
  48. 50. Static Nested class A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used.
  49. 51. <ul><li>Example </li></ul><ul><li>public class MyOuter { </li></ul><ul><ul><li>public static class MyInner { </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>public static void main(String [] args) { </li></ul></ul><ul><ul><li>MyInner aMyInner = new MyOuter.MyInner(); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>} </li></ul><ul><li>Methods of a static inner class cannot use the keyword </li></ul><ul><li>this (either implied or explicit) to access instance variables </li></ul><ul><li>of the enclosing class; those methods can, however, access </li></ul><ul><li>static variables of the enclosing class. </li></ul>
  50. 52. Non Static Nested Class (Inner Class) The most important type of nested class is the inner class . An inner class is a non-static nested class . It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class.
  51. 53. <ul><ul><li>// Demonstrate an inner class. </li></ul></ul><ul><ul><li>class Outer { </li></ul></ul><ul><ul><ul><li>int outer_x = 100; </li></ul></ul></ul><ul><ul><ul><li>void test() { </li></ul></ul></ul><ul><ul><ul><li>Inner inner = new Inner(); </li></ul></ul></ul><ul><ul><ul><li>inner.display(); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>// this is an inner class </li></ul></ul></ul><ul><ul><ul><li>class Inner { </li></ul></ul></ul><ul><ul><ul><ul><li>void display() { </li></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(&quot;display: outer_x = &quot; + outer_x); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul>
  52. 54. <ul><ul><li>class InnerClassDemo { </li></ul></ul><ul><ul><ul><li>public static void main(String args[]) { </li></ul></ul></ul><ul><ul><ul><li>Outer outer = new Outer(); </li></ul></ul></ul><ul><ul><ul><li>outer.test(); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul>
  53. 55. <ul><li>Referring inner class from outside the Outer class </li></ul><ul><ul><li>public static void main(String[] args) { </li></ul></ul><ul><ul><ul><li>Outer mo = new Outer(); </li></ul></ul></ul><ul><ul><ul><li>Outer.Inner inner = Inner(); </li></ul></ul></ul><ul><ul><ul><li>inner.seeOuter(); </li></ul></ul></ul><ul><ul><li>} </li></ul></ul>
  54. 56. <ul><li>Member Modifiers applied to inner Classes </li></ul><ul><ul><li>final </li></ul></ul><ul><ul><li>abstract </li></ul></ul><ul><ul><li>public </li></ul></ul><ul><ul><li>private </li></ul></ul><ul><ul><li>protected </li></ul></ul><ul><ul><li>static— but static turns it into a static nested class not an inner class. </li></ul></ul><ul><ul><li>strictfp </li></ul></ul>
  55. 57. Local class Class defined inside methods Nested classes can be declared in any block, and that this means you can define a class inside a method. Points to consider 1.Anything declared inside a method is not a member of the class, but is local to the method. The immediate consequence is that classes declared in methods are private to the method and cannot be marked with any access modifier; neither can they be marked as static. 2.A method-local inner class can be instantiated only within the method where the inner class is defined. 3. The method-local inner class object can access enclosing (outer) class object private members. Example
  56. 58. The only modifiers you can apply to a method-local inner class are abstract and final, but as always, never both at the same time. Remember that a local class declared in a static method has access to only static members of the enclosing class, since there is no associated instance of the enclosing class. If you're in a static method, there is no this, so an inner class in a static method is subject to the same restrictions as the static method. In other words, no access to instance variables.
  57. 59. <ul><li>Anonymous Inner Classes </li></ul><ul><li>Inner class declared without any class name at all. </li></ul><ul><ul><li>class Popcorn { </li></ul></ul><ul><ul><ul><li>public void pop() { </li></ul></ul></ul><ul><ul><ul><li>System.out.println(&quot;popcorn&quot;); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>class Food { </li></ul></ul><ul><ul><li>Popcorn p = new Popcorn() { </li></ul></ul><ul><ul><ul><ul><li>public void pop() { </li></ul></ul></ul></ul><ul><ul><ul><ul><li>System.out.println(&quot;anonymous popcorn&quot;); </li></ul></ul></ul></ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul><ul><ul><ul><li>}; </li></ul></ul></ul><ul><li>} </li></ul>
  58. 60. We define two classes, Popcorn and Food. * Popcorn has one method, pop(). * Food has one instance variable, declared as type Popcorn. That's it for Food,Food has no methods. The Popcorn reference variable refers not to an instance of Popcorn, but to an instance of an anonymous (unnamed) subclass of Popcorn .
  59. 61. Let's look at just the anonymous class code: 2. Popcorn p = new Popcorn() { 3. public void pop() { 4. System.out.println(&quot;anonymous popcorn&quot;); 5. } 6. }; Line 2 says Declare a reference variable, p, of type Popcorn. Then declare a new class that has no name, but that is a subclass of Popcorn. And here's the curly brace that opens the class definition…
  60. 62. <ul><li>Anonymous Inner Classes, flavor two </li></ul><ul><li>The only difference between flavor one and flavor two is that </li></ul><ul><li>flavor one creates an anonymous subclass of the specified class type, </li></ul><ul><li>whereas flavor two creates an anonymous implementer of the </li></ul><ul><li>specified interface type. </li></ul><ul><li>interface Cookable { </li></ul><ul><li>public void cook(); </li></ul><ul><li>} </li></ul><ul><li>class Food { </li></ul><ul><li>Cookable c = new Cookable() { </li></ul><ul><ul><ul><li>public void cook() { </li></ul></ul></ul><ul><ul><ul><li>System.out.println(&quot;anonymous cookable implementer&quot;); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><li>}; </li></ul><ul><li>} </li></ul>
  61. 63. <ul><li>It's not instantiating a Cookable object, it's creating an </li></ul><ul><li>instance of a new, anonymous, implementer of Cookable. </li></ul><ul><li>The following is not legal, </li></ul><ul><li>Runnable r = new Runnable(); // can't instantiate interface </li></ul><ul><li>whereas the following is legal, because it's instantiating an </li></ul><ul><li>implementer of the Runnable interface </li></ul><ul><li>(an anonymous implementation class): </li></ul><ul><ul><li>Runnable r = new Runnable() { // curly brace, not semicolon </li></ul></ul><ul><ul><li>public void run() { } </li></ul></ul><ul><ul><li>}; </li></ul></ul>
  62. 64. Annotations (Metadata) Annotations are used to embed supplemental information into a source file, this does not change the action of a program. The term Metadata is also used to refer to this feature. Some API’s require “side files” to be maintained in parallel with programs. JavaBeans requires a BeanInfo class to be maintained in parallel with a bean. Enterprise JavaBeans (EJB) requires a deployment descriptor . It would be more convenient and less error-prone if the information in these side files were maintained as annotations in the program itself.
  63. 65. Transient modifier is an ad hoc annotation indicating that a field should be ignored by the serialization subsystem, and the @deprecated javadoc tag is an ad hoc annotation indicating that the method should no longer be used. With the release of JDK5.0 the platform has a general purpose annotation, that permit you to define and use your own annotation types.
  64. 66. Annotations have a number of uses, among them: Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings. Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth. Runtime processing — Some annotations are available to be examined at runtime.
  65. 67. Declaring Annotation public @interface RequestForEnhancement { int id(); String synopsis(); String engineer(); String date(); } Once an annotation type is defined, use it to annotate declarations.
  66. 68. <ul><li>Using Annotations </li></ul><ul><li>Here is a method declaration with an annotation corresponding to the </li></ul><ul><li>annotation type declared above: </li></ul><ul><ul><ul><ul><li>@RequestForEnhancement( </li></ul></ul></ul></ul><ul><ul><ul><ul><li>id = 2868724, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>synopsis = &quot;Enable time-travel&quot;, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>engineer = &quot;Mr. Peabody&quot;, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>date = &quot;4/1/3007&quot; </li></ul></ul></ul></ul><ul><ul><ul><ul><li>) </li></ul></ul></ul></ul><ul><ul><ul><ul><li>public static void travelThroughTime(Date destination) { ... } </li></ul></ul></ul></ul>
  67. 69. Marker Annotation An annotation type with no elements is termed a marker annotation type, for example: public @interface Preliminary { } It is permissible to omit the parentheses in marker annotations, @Preliminary public class TimeTravel { ... }
  68. 70. <ul><li>Annotation with Single Element </li></ul><ul><li>In annotations with a single element, the element should be named </li></ul><ul><li>value, </li></ul><ul><li>public @interface Copyright { String value(); } </li></ul><ul><li>It is permissible to omit the element name and equals sign (=) in a </li></ul><ul><li>single-element annotation whose element name is value, </li></ul><ul><ul><li>@Copyright(&quot;2002 Yoyodyne Propulsion Systems&quot;) </li></ul></ul><ul><ul><li>public class OscillationOverthruster { ... } </li></ul></ul>
  69. 71. Example : Test,Foo,RunTests import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Test { } The annotation type declaration is itself annotated. Such annotations are called meta-annotations . Here @Retention(RetentionPolicy.RUNTIME) indicates that annotations with this type are to be retained by the VM so they can be read reflectively at run-time. @Target(ElementType.METHOD) indicates that this annotation type can be used to annotate only method declarations.
  70. 72. Annotation Examples This example uses reflection to display the annotation associated with a method. This example uses reflection to display the annotation associated with a method having arguments. This example demonstrate how to obtain all annotations That have RUNTIME retention that are associated with an item. This example demonstrate the use of default values in an annotation.