Module 6   Advanced Class Features  
Objectives •  Define overloading, overriding. •  Describe constructor and method overloading •  In a Java program, identify the following:    Overloaded methods and constructors    The use of this to call overloaded constructors Overridden methods The use of super to call parent class methods •  Using static import statement
Objectives •  Java Enumerations  •  Wrapper Classes and Use •  AutoBoxing/Unboxing  •  Annotations(Metadata)  •  Describe  Inner Classes
Overloading Methods When  two or more methods within the same class  share the same name, as long as their parameter declarations  are different,the methods are said to be  overloaded,  and the process is referred to as  method overloading. Method overloading is one of the ways that Java  implements polymorphism. Overloaded methods must differ in the type and/or  number of their parameters. Example  OverloadDemo.java
Note Which over loaded  version of the method to call is based on the  reference  type of the argument passed at  compile  time. Example  UseAnimals.java
Constructors Every class,  including abstract classes , MUST have a constructor. A constructor looks like this: class Foo { Foo() { } // The constructor for the Foo class } Constructors donot have any return type and their name must  exactly match   the class name.
Constructors are used to initialize instance variable state. class Foo { int size; String name; Foo(String name, int size) { this.name = name; this.size = size; } }
Rules for Constructors •  Constructors can use any access modifier, including private. •  The constructor name must match the name of the class. •  Constructors must not have a return type. •  It's legal (but stupid) to have a method with the same name as  the class, but that doesn't make it a constructor. If you see a  return type, it's a method rather than a constructor. •  If you don't type a constructor into your class code, a default  constructor will be automatically generated by the compiler.
•  If you want a no-arg constructor and you've typed any other constructor(s) into your class code, the compiler won't provide the no-arg constructor •  Interfaces do not have constructors. Interfaces are not part of an  object's inheritance tree. •  The first line in a constructor must be a call to super() or a call to this(). Example  OverloadCons.java
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.
•  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.
Examples Legal and Illegal method overrides Consider  public class Animal{ public void eat(){ } }
Example  Consider this example public class Animal { public void eat() { System.out.println("Generic Animal Eating Generically"); } } public class Horse extends Animal { public void eat() { System.out.println("Horse eating hay "); } public void eat(String s) { System.out.println("Horse eating " + s); } } Horse class has both overloaded and overridden the eat() method.
 
 
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  Dispatch.java
Difference between Overloaded and Overridden methods
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
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("x=\t\t"+x);  System.out.println("super.x=\t\t"+super.x);  System.out.println("((T2)this).x=\t"+((T2)this).x);  System.out.println("((T1)this).x=\t"+((T1)this).x);  System.out.println("((I)this).x=\t"+((I)this).x);  }  }  class Test {  public static void main(String[] args) {  new T3().test();  } }
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.
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);
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);
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.
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
•  The identifiers Jonathan,GoldenDel and so on are called  enumeration  constants. •  Each is implicitly declared as public,static final member of Apple. •  Once enumeration is defined ,a variable of that type can be created. •  Even though enumeration define a class type,its not instantiated using new. •  Apple ap, declares  ap  as variable of enumeration type. •  Since ap is of type Apple, the only value that it can be assigned are those defined by enumeration. ap=Apple.RedDel; //assign ap the value RedDel.
•  Two enumeration constants can be compared for equality by  using == operator. if (ap==Apple.GoldenDel) •  An enumeration value can be used to control a switch statement switch(ap){ case Jonathan: //…… case Winesap: //……. } •  When an enumeration constant is displayed such as in println()  statement,its name is output System.out.println(Apple.Winesap); The name Winesap is displayed.
Enums Declaration Outside class   Example CoffeeTest1.java Inside class   Example CoffeeTest2.java 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; } }
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.
enum is a kind of class which look something like this class CoffeeSize { public static final CoffeeSize BIG =new CoffeeSize("BIG", 0); public static final CoffeeSize HUGE =new CoffeeSize("HUGE", 1); public static final CoffeeSize OVERWHELMING = new CoffeeSize("OVERWHELMING", 2); public CoffeeSize(String enumName, int index) { // stuff here } public static void main(String[] args) { System.out.println(CoffeeSize.BIG); } }
Declaring Constructors, Methods and Variables in an enum Example  Coffee.java Remember You can NEVER invoke an enum constructor directly.  The enum constructor is invoked automatically, with the  arguments you define after the constant value. You can define more than one argument to the constructor, and  you can overload the enum constructors, just as you can overload  a normal class constructor.
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
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
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.
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.
Wrapper Classes and their Constructor Arguments
The Wrapper Constructors All of the wrapper classes except Character provide two  constructors:  one that takes a primitive of the type being constructed,  and one that takes a String representation of the type being constructed. Integer i1 = new Integer(42); Integer i2 = new Integer("42"); The Character class provides only one constructor, which takes a  char as an argument Character c1 = new Character('c');
valueOf() Provide an approach to creating wrapper objects. Float f2 = Float.valueOf("3.14f"); // 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();
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("3.14"); // 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("3.14"); System.out.println("d = "+ d.toString() );
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
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();
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().
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  AutoBox.java Autoboxing with method parameters and return values Example  AutoBox2.java
Auto-unboxing also allows to mix different types of numeric  objects in an expression. Integer iOb=100; Double dOb=98.6; dOb=dOb+iOb; Autoboxing/unboxing can also prevent errors. Integer iOb=1000; int i=iOb.byteValue(); System.out.println(i);
What would be the output in the following case Integer i3 = 10; Integer i4 = 10; if(i3 == i4) System.out.println("same object"); if(i3.equals(i4)) System.out.println("meaningfully equal"); Two instances of the following wrapper objects will always be ==  when their primitive values are the same: Boolean Byte Character from \u0000 to \u007f (7f is 127 in decimal) Short and Integer from -128 to 127 This example produces the output: same object meaningfully equal
Overloading with Boxing class AddBoxing { static void go(Integer x) {  System.out.println("Integer");  } static void go(long x) {  System.out.println("long");  } 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
The Object Class   •  The Object class is the root of all classes in Java •  A class declaration with no extends clause, implicitly  uses "extends Object"  public class Employee { ... } is equivalent to: public class Employee extends Object{ ... }
Methods of Object class
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.
Other, access specifiers you may use are  private, public, and protected  There are two types of nested classes:  static  and  non-static .
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.
Example public class MyOuter { public static class MyInner { } public static void main(String [] args) { MyInner aMyInner =  new MyOuter.MyInner(); } } Methods of a static inner class cannot use the keyword  this (either implied or explicit) to access instance variables  of the enclosing class; those methods can, however, access  static variables of the enclosing class.
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.
// Demonstrate an inner class. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } }
class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } }
Referring inner class from outside the Outer class public static void main(String[] args) { Outer mo = new Outer();  Outer.Inner inner = mo.new Inner(); inner.seeOuter(); }
Member Modifiers applied to inner Classes final abstract public private protected static— but  static  turns it into a  static  nested class not an inner class. strictfp
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  MyOuter2.java
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.
Anonymous Inner Classes Inner class declared without any class name at all. class Popcorn { public void pop() { System.out.println("popcorn"); } } class Food { Popcorn p = new Popcorn() { public void pop() { System.out.println("anonymous popcorn"); } }; }
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 .
Let's look at just the anonymous class code: 2. Popcorn p = new Popcorn() { 3.  public void pop() { 4.  System.out.println("anonymous popcorn"); 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…
Anonymous Inner Classes, flavor two The only difference between flavor one and flavor two is that  flavor one creates an anonymous  subclass  of the specified  class  type,  whereas flavor two creates an anonymous  implementer  of the  specified  interface  type. interface Cookable { public void cook(); } class Food { Cookable c = new Cookable() { public void cook() { System.out.println("anonymous cookable implementer"); } }; }
It's not instantiating a Cookable object, it's creating an instance of a new, anonymous, implementer of Cookable. The following is not legal, Runnable r = new Runnable(); // can't instantiate interface whereas the following  is  legal, because it's instantiating an  implementer  of the  Runnable  interface (an anonymous implementation class): Runnable r = new Runnable() { // curly brace, not semicolon public void run() { } };
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.
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.
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.
Declaring Annotation public @interface RequestForEnhancement {  int id();  String synopsis();  String engineer();  String date();  }  Once an annotation type is defined, use it to annotate declarations.
Using Annotations Here is a method declaration with an annotation corresponding to the  annotation type declared above:  @RequestForEnhancement(  id = 2868724,  synopsis = "Enable time-travel",  engineer = "Mr. Peabody",  date = "4/1/3007"  )  public static void travelThroughTime(Date destination) { ... }
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 { ... }
Annotation with Single Element In annotations with a single element, the element should be named  value,  public @interface Copyright { String value(); }  It is permissible to omit the element name and equals sign (=) in a  single-element annotation whose element name is value, @Copyright("2002 Yoyodyne Propulsion Systems")  public class OscillationOverthruster { ... }
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.
Annotation Examples Meta.java This example uses reflection to display the annotation associated with a  method. Meta1.java This example uses reflection to display the annotation associated with a  method having arguments. Meta2.java This example demonstrate how to obtain all annotations That have RUNTIME retention that are associated with an item. Meta3.java This example demonstrate the use of default values in an  annotation.

Md06 advance class features

  • 1.
    Module 6 Advanced Class Features  
  • 2.
    Objectives • Define overloading, overriding. • Describe constructor and method overloading • In a Java program, identify the following: Overloaded methods and constructors The use of this to call overloaded constructors Overridden methods The use of super to call parent class methods • Using static import statement
  • 3.
    Objectives • Java Enumerations • Wrapper Classes and Use • AutoBoxing/Unboxing • Annotations(Metadata) • Describe Inner Classes
  • 4.
    Overloading Methods When two or more methods within the same class share the same name, as long as their parameter declarations are different,the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism. Overloaded methods must differ in the type and/or number of their parameters. Example OverloadDemo.java
  • 5.
    Note Which overloaded version of the method to call is based on the reference type of the argument passed at compile time. Example UseAnimals.java
  • 6.
    Constructors Every class, including abstract classes , MUST have a constructor. A constructor looks like this: class Foo { Foo() { } // The constructor for the Foo class } Constructors donot have any return type and their name must exactly match the class name.
  • 7.
    Constructors are usedto initialize instance variable state. class Foo { int size; String name; Foo(String name, int size) { this.name = name; this.size = size; } }
  • 8.
    Rules for Constructors• Constructors can use any access modifier, including private. • The constructor name must match the name of the class. • Constructors must not have a return type. • It's legal (but stupid) to have a method with the same name as the class, but that doesn't make it a constructor. If you see a return type, it's a method rather than a constructor. • If you don't type a constructor into your class code, a default constructor will be automatically generated by the compiler.
  • 9.
    • Ifyou want a no-arg constructor and you've typed any other constructor(s) into your class code, the compiler won't provide the no-arg constructor • Interfaces do not have constructors. Interfaces are not part of an object's inheritance tree. • The first line in a constructor must be a call to super() or a call to this(). Example OverloadCons.java
  • 10.
    Method Overriding Whena 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.
    • Theaccess 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.
    Examples Legal andIllegal method overrides Consider public class Animal{ public void eat(){ } }
  • 13.
    Example Considerthis example public class Animal { public void eat() { System.out.println("Generic Animal Eating Generically"); } } public class Horse extends Animal { public void eat() { System.out.println("Horse eating hay "); } public void eat(String s) { System.out.println("Horse eating " + s); } } Horse class has both overloaded and overridden the eat() method.
  • 14.
  • 15.
  • 16.
    Note Whichover 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 Dispatch.java
  • 17.
    Difference between Overloadedand Overridden methods
  • 18.
    The Super Keywordsuper 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
  • 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("x=\t\t"+x); System.out.println("super.x=\t\t"+super.x); System.out.println("((T2)this).x=\t"+((T2)this).x); System.out.println("((T1)this).x=\t"+((T1)this).x); System.out.println("((I)this).x=\t"+((I)this).x); } } class Test { public static void main(String[] args) { new T3().test(); } }
  • 20.
    Static import StatementThis 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.
  • 21.
    The java.lang.Math classdefines 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);
  • 22.
    Use the staticimport 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);
  • 23.
    Enumerations With JDK5.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.
  • 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
  • 25.
    • Theidentifiers Jonathan,GoldenDel and so on are called enumeration constants. • Each is implicitly declared as public,static final member of Apple. • Once enumeration is defined ,a variable of that type can be created. • Even though enumeration define a class type,its not instantiated using new. • Apple ap, declares ap as variable of enumeration type. • Since ap is of type Apple, the only value that it can be assigned are those defined by enumeration. ap=Apple.RedDel; //assign ap the value RedDel.
  • 26.
    • Twoenumeration constants can be compared for equality by using == operator. if (ap==Apple.GoldenDel) • An enumeration value can be used to control a switch statement switch(ap){ case Jonathan: //…… case Winesap: //……. } • When an enumeration constant is displayed such as in println() statement,its name is output System.out.println(Apple.Winesap); The name Winesap is displayed.
  • 27.
    Enums Declaration Outsideclass Example CoffeeTest1.java Inside class Example CoffeeTest2.java 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; } }
  • 28.
    Answer Compile timeerror, 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.
  • 29.
    enum is akind of class which look something like this class CoffeeSize { public static final CoffeeSize BIG =new CoffeeSize("BIG", 0); public static final CoffeeSize HUGE =new CoffeeSize("HUGE", 1); public static final CoffeeSize OVERWHELMING = new CoffeeSize("OVERWHELMING", 2); public CoffeeSize(String enumName, int index) { // stuff here } public static void main(String[] args) { System.out.println(CoffeeSize.BIG); } }
  • 30.
    Declaring Constructors, Methodsand Variables in an enum Example Coffee.java Remember You can NEVER invoke an enum constructor directly. The enum constructor is invoked automatically, with the arguments you define after the constant value. You can define more than one argument to the constructor, and you can overload the enum constructors, just as you can overload a normal class constructor.
  • 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
  • 32.
    Java Enumerations areClass 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
  • 33.
    Enumerations Inherit EnumIts 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.
  • 34.
    Wrapper Classes Javause 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.
  • 35.
    Wrapper Classes andtheir Constructor Arguments
  • 36.
    The Wrapper ConstructorsAll of the wrapper classes except Character provide two constructors: one that takes a primitive of the type being constructed, and one that takes a String representation of the type being constructed. Integer i1 = new Integer(42); Integer i2 = new Integer("42"); The Character class provides only one constructor, which takes a char as an argument Character c1 = new Character('c');
  • 37.
    valueOf() Provide anapproach to creating wrapper objects. Float f2 = Float.valueOf("3.14f"); // 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();
  • 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("3.14"); // 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("3.14"); System.out.println("d = "+ d.toString() );
  • 39.
    In summary, theessential 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
  • 40.
    Boxing The processof 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();
  • 41.
    Autoboxing/unboxing With JDK5, 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().
  • 42.
    The modern wayto 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 AutoBox.java Autoboxing with method parameters and return values Example AutoBox2.java
  • 43.
    Auto-unboxing also allowsto mix different types of numeric objects in an expression. Integer iOb=100; Double dOb=98.6; dOb=dOb+iOb; Autoboxing/unboxing can also prevent errors. Integer iOb=1000; int i=iOb.byteValue(); System.out.println(i);
  • 44.
    What would bethe output in the following case Integer i3 = 10; Integer i4 = 10; if(i3 == i4) System.out.println("same object"); if(i3.equals(i4)) System.out.println("meaningfully equal"); Two instances of the following wrapper objects will always be == when their primitive values are the same: Boolean Byte Character from \u0000 to \u007f (7f is 127 in decimal) Short and Integer from -128 to 127 This example produces the output: same object meaningfully equal
  • 45.
    Overloading with Boxingclass AddBoxing { static void go(Integer x) { System.out.println("Integer"); } static void go(long x) { System.out.println("long"); } 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
  • 46.
    The Object Class • The Object class is the root of all classes in Java • A class declaration with no extends clause, implicitly uses "extends Object" public class Employee { ... } is equivalent to: public class Employee extends Object{ ... }
  • 47.
  • 48.
    Nested and InnerClass 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.
  • 49.
    Other, access specifiersyou may use are private, public, and protected There are two types of nested classes: static and non-static .
  • 50.
    Static Nested classA 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.
  • 51.
    Example public classMyOuter { public static class MyInner { } public static void main(String [] args) { MyInner aMyInner = new MyOuter.MyInner(); } } Methods of a static inner class cannot use the keyword this (either implied or explicit) to access instance variables of the enclosing class; those methods can, however, access static variables of the enclosing class.
  • 52.
    Non Static NestedClass (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.
  • 53.
    // Demonstrate aninner class. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } }
  • 54.
    class InnerClassDemo {public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } }
  • 55.
    Referring inner classfrom outside the Outer class public static void main(String[] args) { Outer mo = new Outer(); Outer.Inner inner = mo.new Inner(); inner.seeOuter(); }
  • 56.
    Member Modifiers appliedto inner Classes final abstract public private protected static— but static turns it into a static nested class not an inner class. strictfp
  • 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 MyOuter2.java
  • 58.
    The only modifiersyou 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.
  • 59.
    Anonymous Inner ClassesInner class declared without any class name at all. class Popcorn { public void pop() { System.out.println("popcorn"); } } class Food { Popcorn p = new Popcorn() { public void pop() { System.out.println("anonymous popcorn"); } }; }
  • 60.
    We define twoclasses, 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 .
  • 61.
    Let's look atjust the anonymous class code: 2. Popcorn p = new Popcorn() { 3. public void pop() { 4. System.out.println("anonymous popcorn"); 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…
  • 62.
    Anonymous Inner Classes,flavor two The only difference between flavor one and flavor two is that flavor one creates an anonymous subclass of the specified class type, whereas flavor two creates an anonymous implementer of the specified interface type. interface Cookable { public void cook(); } class Food { Cookable c = new Cookable() { public void cook() { System.out.println("anonymous cookable implementer"); } }; }
  • 63.
    It's not instantiatinga Cookable object, it's creating an instance of a new, anonymous, implementer of Cookable. The following is not legal, Runnable r = new Runnable(); // can't instantiate interface whereas the following is legal, because it's instantiating an implementer of the Runnable interface (an anonymous implementation class): Runnable r = new Runnable() { // curly brace, not semicolon public void run() { } };
  • 64.
    Annotations (Metadata) Annotationsare 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.
  • 65.
    Transient modifier isan 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.
  • 66.
    Annotations have anumber 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.
  • 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.
  • 68.
    Using Annotations Hereis a method declaration with an annotation corresponding to the annotation type declared above: @RequestForEnhancement( id = 2868724, synopsis = "Enable time-travel", engineer = "Mr. Peabody", date = "4/1/3007" ) public static void travelThroughTime(Date destination) { ... }
  • 69.
    Marker AnnotationAn 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 { ... }
  • 70.
    Annotation with SingleElement In annotations with a single element, the element should be named value, public @interface Copyright { String value(); } It is permissible to omit the element name and equals sign (=) in a single-element annotation whose element name is value, @Copyright("2002 Yoyodyne Propulsion Systems") public class OscillationOverthruster { ... }
  • 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.
  • 72.
    Annotation Examples Meta.javaThis example uses reflection to display the annotation associated with a method. Meta1.java This example uses reflection to display the annotation associated with a method having arguments. Meta2.java This example demonstrate how to obtain all annotations That have RUNTIME retention that are associated with an item. Meta3.java This example demonstrate the use of default values in an annotation.