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 UseAnimals.java
6.
7. 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; } }
8.
9.
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. • 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. Examples Legal and Illegal method overrides Consider public class Animal{ public void eat(){ } }
13.
14.
15.
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 Dispatch.java
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
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="+x); System.out.println("super.x="+super.x); System.out.println("((T2)this).x="+((T2)this).x); System.out.println("((T1)this).x="+((T1)this).x); System.out.println("((I)this).x="+((I)this).x); } } class Test { public static void main(String[] args) { new T3().test(); } }
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.
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);
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);
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.
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.
26.
27. 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; } }
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.
29. 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); } }
30.
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 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
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.
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.
37. 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();
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, 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
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();
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().
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 AutoBox.java Autoboxing with method parameters and return values Example AutoBox2.java
43.
44.
45. 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
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.
49.
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.
51.
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.
53.
54.
55.
56.
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 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.
59.
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 .
61. 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…
62.
63.
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.
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.
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.
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.
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 { ... }
70.
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.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.