SlideShare a Scribd company logo
1 of 24
Inheritance and Polymorphism

          Chapter 9




                      1
Polymorphism, Dynamic Binding and Generic Programming
public class Test {
  public static void main(String[] args) {
    m(new GraduateStudent());                        Method m takes a parameter
    m(new Student());
    m(new Person());
                                                     of the Object type. You can
    m(new Object());                                 invoke it with any object.
  }

    public static void m(Object x) {         An object of a subtype can be used wherever its
      System.out.println(x.toString());
    }                                        supertype value is required. This feature is
}
                                             known as polymorphism.
class GraduateStudent extends Student {
}

class Student extends Person {               When the method m(Object x) is executed, the
  public String toString() {
    return "Student";
                                             argument x’s toString method is invoked. x
  }                                          may be an instance of GraduateStudent,
}
                                             Student, Person, or Object. Classes
class Person extends Object {                GraduateStudent, Student, Person, and Object
  public String toString() {
    return "Person";                         have their own implementation of the toString
}
  }                                          method. Which implementation is used will be
                                             determined dynamically by the Java Virtual
                                             Machine at runtime. This capability is known
                                             as dynamic binding.
                                                                      2
Dynamic Binding
Dynamic binding works as follows: Suppose an object o is an
instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass of
C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That is, Cn
is the most general class, and C1 is the most specific class. In
Java, Cn is the Object class. If o invokes a method p, the JVM
searches the implementation for the method p in C1, C2, ..., Cn-1 and
Cn, in this order, until it is found. Once an implementation is
found, the search stops and the first-found implementation is
invoked.
   Cn          Cn-1           .....                C2              C1

                                      Since o is an instance of C1, o is also an
Object                                instance of C2, C3, …, Cn-1, and Cn


                                                           3
Method Matching vs. Binding
Matching a method signature and binding a method
implementation are two issues.
•Compiler finds a matching method according to parameter
type, number of parameters, and order of the parameters at
compilation time. A method may be implemented in several
subclasses.
•Java Virtual Machine dynamically binds the implementation of
the method at runtime.
•See Review Questions 9.7 and 9.8.




                                             4
Generic Programming
public class Test {
  public static void main(String[] args) {   Polymorphism allows methods to be used
    m(new GraduateStudent());                generically for a wide range of object
    m(new Student());
    m(new Person());
                                             arguments. This is known as generic
    m(new Object());                         programming.
  }                                          If a method’s parameter type is a
    public static void m(Object x) {         superclass (e.g., Object), you may pass an
      System.out.println(x.toString());      object to this method of any of the
    }                                        parameter’s subclasses (e.g., Student or
}
                                             GraduateStudent).
class GraduateStudent extends Student {      When an object (e.g., a Student object or
}
                                             a GraduateStudent object) is used in the
class Student extends Person {               method, the particular implementation of
  public String toString() {                 the method of the object that is invoked
  }
    return "Student";                        (e.g., toString) is determined dynamically.
}

class Person extends Object {
  public String toString() {
    return "Person";
  }
}




                                                                  5
Example
•   Polymorphism2 project
•   FindArea project in Polymorphism
•   FindArea2 project in Polymorphism
•   Discussion: Why is it neat?




                                 6
Casting Objects
You have already used the casting operator to convert variables of
one primitive type to another. Casting can also be used to convert an
object of one class type to another within an inheritance hierarchy. In
the preceding section, the statement
   m(new Student());

assigns the object new Student() to a parameter of the Object type.
This statement is equivalent to:
   Object o = new Student(); // Implicit casting
   m(o);

                             The statement Object o = new Student(), known as
                             implicit casting, is legal because an instance of
                             Student is automatically an instance of Object.


                                                            7
Why Casting Is Necessary?
Suppose you want to assign the object reference o to a variable of the
Student type using the following statement:
   Object o;
   Student b = o;       // A compilation error would occur.
But
   Object o = new Student(); // compiles

Reason: A Student object is always an instance of Object, but
an Object is not necessarily an instance of Student. The
compiler is not so clever.

Remedy: Use an explicit casting.
   Student b = (Student)o; // Explicit casting




                                                        8
Casting from
      Superclass to Subclass
Explicit casting must be used when casting
an object from a superclass to a subclass.
This type of casting may not always succeed.
  Cylinder myCylinder = (Cylinder)myCircle;

  Apple x = (Apple)fruit;

  Orange x = (Orange)fruit;

                                 9
The instanceof Operator

Defensive programming:
Use the instanceof operator to test whether an
object is an instance of a class. If so, you can cast it:
Circle myCircle = new Circle();

if (myCircle instanceof Cylinder) {
  Cylinder myCylinder = (Cylinder)myCircle;
  ...
}




                                           10
TIP: To help understand casting
Compare fruit - {apple, orange} with
Fruit superclass -{Apple , Orange}
An apple is a fruit, so assigning an instance
of Apple to a variable for Fruit is safe.
However, a fruit is not necessarily an apple,
so must use explicit casting to assign an
instance of Fruit to a variable of Apple.


                                  11
Demonstrating Polymorphism
             and Casting
Example:
creates two geometric objects: a circle, and a cylinder;
invokes the displayGeometricObject method to display
the objects.
The displayGeometricObject displays the area and
perimeter if the object is a circle, and displays area and
volume if the object is a cylinder.

See BJ_Polymorphism_Casting

                                              12
Other notables




                 13
A Subclass Cannot Weaken the
            Accessibility
A subclass may override a protected
method in its superclass and change its
visibility to public. However, a subclass
cannot weaken the accessibility of a
method defined in the superclass. For
example, if a method is defined as public
in the superclass, it must be defined as
public in the subclass.

                                14
The final Modifier
• The final class cannot be extended:
   final class Math {
    ...
   }

• The final variable is a constant:
   final static double PI = 3.14159;

• The final method cannot be
  overridden by its subclasses.


                                      15
Optional
           The equals() and hashCode()
           Methods in the Object Class
 • The equals() method compares the
   contents of two objects.

 • The hashCode() method returns the hash
   code of the object. Hash code is an
   integer, which can be used to store the
   object in a hash set so that it can be
   located quickly.
                                 16
The equals Method
The equals() method compares the
contents of two objects. The default implementation
of the equals method in the Object class is as
follows:
     public boolean equals(Object obj) {


For example, the   public boolean equals(Object o) {
equals method is     if (o instanceof Circle) {
overridden in          return radius == ((Circle)o).radius;
                     }
the Circle           else
class.                 return false;
                   }



                                            17
NOTE: == vs equal()
The == comparison operator compares
•two primitive data type values or
•whether two objects have the same references.
The equals method tests
•whether two objects have the same contents, provided that
the method is modified in the defining class of the objects.
•== operator is stronger than the equals method, in that the
== operator checks whether the two reference variables refer
to the same object.

                                             18
The hashCode() method
object.hashCode() returns the hash code of the object.

Hash code is an integer, which can be used to store the object
in a hash set so that it can be located quickly.

Hash sets will be discussed in “Java Collections Framework.”

The hashCode implemented in the Object class returns the
internal memory address of the object in hexadecimal.

Your class should override the hashCode method whenever
the equals method is overridden.

By contract, if two objects are equal, their hash codes must be
same.
                                              19
Optional
           The finalize, clone, and
             getClass Methods
  •The finalize method is invoked by the garbage
  collector on an object when the object becomes
  garbage.
  •The clone() method copies an object.

  •The getClass() method returns an instance of
  the java.lang.Class class, which contains the
  information about the class for the object. You
  can get the information about the class at
  runtime.
                                      20
Initialization Block (optional)
    Initialization blocks can be used to initialize objects along with the
    constructors. An initialization block is a block of statements enclosed inside
    a pair of braces. An initialization block appears within the class declaration,
    but not inside methods or constructors. It is executed as if it were placed at
    the beginning of every constructor in the class.
public class Book {                                public class Book {
  private static int numOfObjects;                   private static int numOfObjects;
  private String title                               private String title;
  private int id;                                    private int id;
                                      Equivalent
    public Book(String title) {                        public Book(String title) {
      this.title = title;                                numOfObjects++;
    }                                                    this.title = title;
                                                       }
    public Book(int id) {
      this.id = id;                                    public Book(int id) {
    }                                                    numOfObjects++;
                                                         this.id = id;
    {                                                  }
        numOfObjects++;                            }
    }
}

                                                                21
Initialization Block
public class Book {
    {
        numOfObjects++;
    }
}



                               22
Static Initialization Block
A static initialization block is much like a
nonstatic initialization block except that it is
declared static, can only refer to static
members of the class, and is invoked when
the class is loaded. The JVM loads a class
when it is needed. A superclass is loaded
before its subclasses.



                                      23
Static Initialization Block
class A extends B {
static {
        System.out.println("A's static initialization block " +
         "is invoked");
    }
}


class B {
static {
        System.out.println("B's static initialization block " +
         “is invoked");
    }
}


                                                      24

More Related Content

What's hot (20)

Farhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd YearFarhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd Year
 
Java Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O MechanismsJava Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O Mechanisms
 
11slide
11slide11slide
11slide
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Xml Path Language1.0
Xml Path Language1.0Xml Path Language1.0
Xml Path Language1.0
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Objective c
Objective cObjective c
Objective c
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
10slide
10slide10slide
10slide
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
 
Java02
Java02Java02
Java02
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Java basic
Java basicJava basic
Java basic
 
Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3
 

Viewers also liked

Get Social with StarBuzz Social Web Community
Get Social with StarBuzz Social Web Community Get Social with StarBuzz Social Web Community
Get Social with StarBuzz Social Web Community StarBuzz Weekly
 
Sinh vienit.net --bao-cao-design_patterns
Sinh vienit.net --bao-cao-design_patternsSinh vienit.net --bao-cao-design_patterns
Sinh vienit.net --bao-cao-design_patternshaduyen757
 
Design Patterns Course
Design Patterns CourseDesign Patterns Course
Design Patterns CourseAhmed Soliman
 
Phani Kumar - Decorator Pattern
Phani Kumar - Decorator PatternPhani Kumar - Decorator Pattern
Phani Kumar - Decorator Patternmelbournepatterns
 
Presenter and Decorator in Rails
Presenter and Decorator in RailsPresenter and Decorator in Rails
Presenter and Decorator in RailsThaichor Seng
 
Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)Sameer Rathoud
 
Design Pattern lecture 3
Design Pattern lecture 3Design Pattern lecture 3
Design Pattern lecture 3Julie Iskander
 
Decorator Design Pattern
Decorator Design PatternDecorator Design Pattern
Decorator Design PatternAdeel Riaz
 
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator PatternDesign Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator Patterneprafulla
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator PatternJonathan Simon
 

Viewers also liked (18)

Get Social with StarBuzz Social Web Community
Get Social with StarBuzz Social Web Community Get Social with StarBuzz Social Web Community
Get Social with StarBuzz Social Web Community
 
17 sessions
17 sessions17 sessions
17 sessions
 
12 cache questions
12 cache questions12 cache questions
12 cache questions
 
Sinh vienit.net --bao-cao-design_patterns
Sinh vienit.net --bao-cao-design_patternsSinh vienit.net --bao-cao-design_patterns
Sinh vienit.net --bao-cao-design_patterns
 
16 cookies
16 cookies16 cookies
16 cookies
 
Decorator
DecoratorDecorator
Decorator
 
Design Patterns Course
Design Patterns CourseDesign Patterns Course
Design Patterns Course
 
Phani Kumar - Decorator Pattern
Phani Kumar - Decorator PatternPhani Kumar - Decorator Pattern
Phani Kumar - Decorator Pattern
 
Presenter and Decorator in Rails
Presenter and Decorator in RailsPresenter and Decorator in Rails
Presenter and Decorator in Rails
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
15 decorator pattern
15 decorator pattern15 decorator pattern
15 decorator pattern
 
Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)Decorator design pattern (A Gift Wrapper)
Decorator design pattern (A Gift Wrapper)
 
Decorator design pattern
Decorator design patternDecorator design pattern
Decorator design pattern
 
12 memory hierarchy
12 memory hierarchy12 memory hierarchy
12 memory hierarchy
 
Design Pattern lecture 3
Design Pattern lecture 3Design Pattern lecture 3
Design Pattern lecture 3
 
Decorator Design Pattern
Decorator Design PatternDecorator Design Pattern
Decorator Design Pattern
 
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator PatternDesign Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator Pattern
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator Pattern
 

Similar to 8 polymorphism

‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3Mahmoud Alfarra
 
JAVA Polymorphism
JAVA PolymorphismJAVA Polymorphism
JAVA PolymorphismMahi Mca
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsHelen SagayaRaj
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxRAJASEKHARV10
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismIt Academy
 

Similar to 8 polymorphism (20)

‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
JAVA Polymorphism
JAVA PolymorphismJAVA Polymorphism
JAVA Polymorphism
 
Java OO Revisited
Java OO RevisitedJava OO Revisited
Java OO Revisited
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Java Concepts
Java ConceptsJava Concepts
Java Concepts
 
Hemajava
HemajavaHemajava
Hemajava
 
CHAPTER 3 part2.pdf
CHAPTER 3 part2.pdfCHAPTER 3 part2.pdf
CHAPTER 3 part2.pdf
 
Core java oop
Core java oopCore java oop
Core java oop
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Chapter8:Understanding Polymorphism
Chapter8:Understanding PolymorphismChapter8:Understanding Polymorphism
Chapter8:Understanding Polymorphism
 
Java basics
Java basicsJava basics
Java basics
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 

8 polymorphism

  • 2. Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[] args) { m(new GraduateStudent()); Method m takes a parameter m(new Student()); m(new Person()); of the Object type. You can m(new Object()); invoke it with any object. } public static void m(Object x) { An object of a subtype can be used wherever its System.out.println(x.toString()); } supertype value is required. This feature is } known as polymorphism. class GraduateStudent extends Student { } class Student extends Person { When the method m(Object x) is executed, the public String toString() { return "Student"; argument x’s toString method is invoked. x } may be an instance of GraduateStudent, } Student, Person, or Object. Classes class Person extends Object { GraduateStudent, Student, Person, and Object public String toString() { return "Person"; have their own implementation of the toString } } method. Which implementation is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding. 2
  • 3. Dynamic Binding Dynamic binding works as follows: Suppose an object o is an instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That is, Cn is the most general class, and C1 is the most specific class. In Java, Cn is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C1, C2, ..., Cn-1 and Cn, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked. Cn Cn-1 ..... C2 C1 Since o is an instance of C1, o is also an Object instance of C2, C3, …, Cn-1, and Cn 3
  • 4. Method Matching vs. Binding Matching a method signature and binding a method implementation are two issues. •Compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compilation time. A method may be implemented in several subclasses. •Java Virtual Machine dynamically binds the implementation of the method at runtime. •See Review Questions 9.7 and 9.8. 4
  • 5. Generic Programming public class Test { public static void main(String[] args) { Polymorphism allows methods to be used m(new GraduateStudent()); generically for a wide range of object m(new Student()); m(new Person()); arguments. This is known as generic m(new Object()); programming. } If a method’s parameter type is a public static void m(Object x) { superclass (e.g., Object), you may pass an System.out.println(x.toString()); object to this method of any of the } parameter’s subclasses (e.g., Student or } GraduateStudent). class GraduateStudent extends Student { When an object (e.g., a Student object or } a GraduateStudent object) is used in the class Student extends Person { method, the particular implementation of public String toString() { the method of the object that is invoked } return "Student"; (e.g., toString) is determined dynamically. } class Person extends Object { public String toString() { return "Person"; } } 5
  • 6. Example • Polymorphism2 project • FindArea project in Polymorphism • FindArea2 project in Polymorphism • Discussion: Why is it neat? 6
  • 7. Casting Objects You have already used the casting operator to convert variables of one primitive type to another. Casting can also be used to convert an object of one class type to another within an inheritance hierarchy. In the preceding section, the statement m(new Student()); assigns the object new Student() to a parameter of the Object type. This statement is equivalent to: Object o = new Student(); // Implicit casting m(o); The statement Object o = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object. 7
  • 8. Why Casting Is Necessary? Suppose you want to assign the object reference o to a variable of the Student type using the following statement: Object o; Student b = o; // A compilation error would occur. But Object o = new Student(); // compiles Reason: A Student object is always an instance of Object, but an Object is not necessarily an instance of Student. The compiler is not so clever. Remedy: Use an explicit casting. Student b = (Student)o; // Explicit casting 8
  • 9. Casting from Superclass to Subclass Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Cylinder myCylinder = (Cylinder)myCircle; Apple x = (Apple)fruit; Orange x = (Orange)fruit; 9
  • 10. The instanceof Operator Defensive programming: Use the instanceof operator to test whether an object is an instance of a class. If so, you can cast it: Circle myCircle = new Circle(); if (myCircle instanceof Cylinder) { Cylinder myCylinder = (Cylinder)myCircle; ... } 10
  • 11. TIP: To help understand casting Compare fruit - {apple, orange} with Fruit superclass -{Apple , Orange} An apple is a fruit, so assigning an instance of Apple to a variable for Fruit is safe. However, a fruit is not necessarily an apple, so must use explicit casting to assign an instance of Fruit to a variable of Apple. 11
  • 12. Demonstrating Polymorphism and Casting Example: creates two geometric objects: a circle, and a cylinder; invokes the displayGeometricObject method to display the objects. The displayGeometricObject displays the area and perimeter if the object is a circle, and displays area and volume if the object is a cylinder. See BJ_Polymorphism_Casting 12
  • 14. A Subclass Cannot Weaken the Accessibility A subclass may override a protected method in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass. 14
  • 15. The final Modifier • The final class cannot be extended: final class Math { ... } • The final variable is a constant: final static double PI = 3.14159; • The final method cannot be overridden by its subclasses. 15
  • 16. Optional The equals() and hashCode() Methods in the Object Class • The equals() method compares the contents of two objects. • The hashCode() method returns the hash code of the object. Hash code is an integer, which can be used to store the object in a hash set so that it can be located quickly. 16
  • 17. The equals Method The equals() method compares the contents of two objects. The default implementation of the equals method in the Object class is as follows: public boolean equals(Object obj) { For example, the public boolean equals(Object o) { equals method is if (o instanceof Circle) { overridden in return radius == ((Circle)o).radius; } the Circle else class. return false; } 17
  • 18. NOTE: == vs equal() The == comparison operator compares •two primitive data type values or •whether two objects have the same references. The equals method tests •whether two objects have the same contents, provided that the method is modified in the defining class of the objects. •== operator is stronger than the equals method, in that the == operator checks whether the two reference variables refer to the same object. 18
  • 19. The hashCode() method object.hashCode() returns the hash code of the object. Hash code is an integer, which can be used to store the object in a hash set so that it can be located quickly. Hash sets will be discussed in “Java Collections Framework.” The hashCode implemented in the Object class returns the internal memory address of the object in hexadecimal. Your class should override the hashCode method whenever the equals method is overridden. By contract, if two objects are equal, their hash codes must be same. 19
  • 20. Optional The finalize, clone, and getClass Methods •The finalize method is invoked by the garbage collector on an object when the object becomes garbage. •The clone() method copies an object. •The getClass() method returns an instance of the java.lang.Class class, which contains the information about the class for the object. You can get the information about the class at runtime. 20
  • 21. Initialization Block (optional) Initialization blocks can be used to initialize objects along with the constructors. An initialization block is a block of statements enclosed inside a pair of braces. An initialization block appears within the class declaration, but not inside methods or constructors. It is executed as if it were placed at the beginning of every constructor in the class. public class Book { public class Book { private static int numOfObjects; private static int numOfObjects; private String title private String title; private int id; private int id; Equivalent public Book(String title) { public Book(String title) { this.title = title; numOfObjects++; } this.title = title; } public Book(int id) { this.id = id; public Book(int id) { } numOfObjects++; this.id = id; { } numOfObjects++; } } } 21
  • 22. Initialization Block public class Book { { numOfObjects++; } } 22
  • 23. Static Initialization Block A static initialization block is much like a nonstatic initialization block except that it is declared static, can only refer to static members of the class, and is invoked when the class is loaded. The JVM loads a class when it is needed. A superclass is loaded before its subclasses. 23
  • 24. Static Initialization Block class A extends B { static { System.out.println("A's static initialization block " + "is invoked"); } } class B { static { System.out.println("B's static initialization block " + “is invoked"); } } 24