SlideShare a Scribd company logo
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.
Ad

More Related Content

What's hot (20)

Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
Elizabeth alexander
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
DevaKumari Vijay
 
The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1
İbrahim Kürce
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
Sherihan Anver
 
Java interview
Java interviewJava interview
Java interview
Mohammad Shahban
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
Shivam Singhal
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
Thakur Amit Tomer
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
dplunkett
 
Java Basics
Java BasicsJava Basics
Java Basics
Dhanunjai Bandlamudi
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
Ahsan Raja
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
Sean McElrath
 
Ppt chapter11
Ppt chapter11Ppt chapter11
Ppt chapter11
Richard Styner
 
Comparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussionComparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussion
Dharmendra Prasad
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
İbrahim Kürce
 
Refactoring bad codesmell
Refactoring bad codesmellRefactoring bad codesmell
Refactoring bad codesmell
hyunglak kim
 
Ppt chapter09
Ppt chapter09Ppt chapter09
Ppt chapter09
Richard Styner
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
CharthaGaglani
 
Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
arnold 7490
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
DevaKumari Vijay
 
The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1
İbrahim Kürce
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
Sherihan Anver
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
Shivam Singhal
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
dplunkett
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
Ahsan Raja
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
Sean McElrath
 
Comparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussionComparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussion
Dharmendra Prasad
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
İbrahim Kürce
 
Refactoring bad codesmell
Refactoring bad codesmellRefactoring bad codesmell
Refactoring bad codesmell
hyunglak kim
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
CharthaGaglani
 

Similar to Md06 advance class features (20)

Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
Rakesh Madugula
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
Todor Kolev
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
Todor Kolev
 
Enumerations in java.pptx
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptx
Srizan Pokrel
 
Java Tokens in java program . pptx
Java Tokens in  java program   .    pptxJava Tokens in  java program   .    pptx
Java Tokens in java program . pptx
CmDept
 
7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf
simukondasankananji8
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
Epsiba1
 
Module 1 full slidfcccccccccccccccccccccccccccccccccccdes.pptx
Module 1 full slidfcccccccccccccccccccccccccccccccccccdes.pptxModule 1 full slidfcccccccccccccccccccccccccccccccccccdes.pptx
Module 1 full slidfcccccccccccccccccccccccccccccccccccdes.pptx
rishiskj
 
Java
JavaJava
Java
nirbhayverma8
 
Learn java
Learn javaLearn java
Learn java
Palahuja
 
Week 7 Java Programming Methods For I.T students.pdf
Week 7 Java Programming Methods For I.T students.pdfWeek 7 Java Programming Methods For I.T students.pdf
Week 7 Java Programming Methods For I.T students.pdf
JaypeeGPolancos
 
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt123 JAVA CLASSES, OBJECTS AND METHODS.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
Unit 7 inheritance
Unit 7 inheritanceUnit 7 inheritance
Unit 7 inheritance
atcnerd
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
Rakesh Madugula
 
14 interface
14  interface14  interface
14 interface
Ravindra Rathore
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
SOEN6441.genericsSOEN6441.genericsSOEN6441.generics
SOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.generics
SOEN6441.genericsSOEN6441.genericsSOEN6441.generics
tahircs1
 
SOEN6441.generics.ppt
SOEN6441.generics.pptSOEN6441.generics.ppt
SOEN6441.generics.ppt
ElieMambou1
 
M C6java3
M C6java3M C6java3
M C6java3
mbruggen
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
Hamad Odhabi
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
Todor Kolev
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
Todor Kolev
 
Enumerations in java.pptx
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptx
Srizan Pokrel
 
Java Tokens in java program . pptx
Java Tokens in  java program   .    pptxJava Tokens in  java program   .    pptx
Java Tokens in java program . pptx
CmDept
 
7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf7. VARIABLEs presentation in java programming. Pdf
7. VARIABLEs presentation in java programming. Pdf
simukondasankananji8
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
Epsiba1
 
Module 1 full slidfcccccccccccccccccccccccccccccccccccdes.pptx
Module 1 full slidfcccccccccccccccccccccccccccccccccccdes.pptxModule 1 full slidfcccccccccccccccccccccccccccccccccccdes.pptx
Module 1 full slidfcccccccccccccccccccccccccccccccccccdes.pptx
rishiskj
 
Learn java
Learn javaLearn java
Learn java
Palahuja
 
Week 7 Java Programming Methods For I.T students.pdf
Week 7 Java Programming Methods For I.T students.pdfWeek 7 Java Programming Methods For I.T students.pdf
Week 7 Java Programming Methods For I.T students.pdf
JaypeeGPolancos
 
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt123 JAVA CLASSES, OBJECTS AND METHODS.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
mcjaya2024
 
Unit 7 inheritance
Unit 7 inheritanceUnit 7 inheritance
Unit 7 inheritance
atcnerd
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
SOEN6441.genericsSOEN6441.genericsSOEN6441.generics
SOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.generics
SOEN6441.genericsSOEN6441.genericsSOEN6441.generics
tahircs1
 
SOEN6441.generics.ppt
SOEN6441.generics.pptSOEN6441.generics.ppt
SOEN6441.generics.ppt
ElieMambou1
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
Hamad Odhabi
 
Ad

More from Rakesh Madugula (11)

New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
Rakesh Madugula
 
Md121 streams
Md121 streamsMd121 streams
Md121 streams
Rakesh Madugula
 
Md11 gui event handling
Md11 gui event handlingMd11 gui event handling
Md11 gui event handling
Rakesh Madugula
 
Md10 building java gu is
Md10 building java gu isMd10 building java gu is
Md10 building java gu is
Rakesh Madugula
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Rakesh Madugula
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
Rakesh Madugula
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Md05 arrays
Md05 arraysMd05 arrays
Md05 arrays
Rakesh Madugula
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
Rakesh Madugula
 
Ad

Recently uploaded (20)

Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 

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 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. 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 used to 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. • 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
  • 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. 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.
  • 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
  • 17. Difference between Overloaded and Overridden methods
  • 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=\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 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. • 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.
  • 26. • 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.
  • 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. 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.
  • 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.
  • 35. Wrapper Classes and their Constructor Arguments
  • 36. 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');
  • 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. 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);
  • 44. 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
  • 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
  • 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{ ... }
  • 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. Other, access specifiers you may use are private, public, and protected There are two types of nested classes: static and non-static .
  • 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. 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.
  • 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. // 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); } } }
  • 54. class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } }
  • 55. 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(); }
  • 56. 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
  • 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. 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"); } }; }
  • 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. 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 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() { } };
  • 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. 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) { ... }
  • 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. 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 { ... }
  • 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.