SlideShare a Scribd company logo
The Object Class
• Every java class has Object as its superclass and thus
inherits the Object methods.
• Object is a non-abstract class
• Many Object methods, however, have
implementations that aren’t particularly useful in
general
• In most cases it is a good idea to override these
methods with more useful versions.
• In other cases it is required if you want your objects
to correctly work with other class libraries.
Clone Method
• Recall that the “=“ operator simply copies Object
references. e.g.,
>> Student s1 = new Student(“Smith”, Jim, 3.13);
>> Student s2 = s1;
>> s1.setName(“Sahil”);
>> System.out.println(s2.getName());
OP:- Sahil
• What if we want to actually make a copy of an Object?
• Most elegant way is to use the clone() method inherited
from Object.
Student s2 = (Student) s1.clone();
About clone() method

• First, note that the clone method is protected in the Object
class.
• This means that it is protected for subclasses as well.
• Hence, it cannot be called from within an Object of another
class and package.
• To use the clone method, you must override in your
subclass and upgrade visibility to public.
• Also, any class that uses clone must implement the
Cloneable interface.
• This is a bit different from other interfaces that we’ve seen.
• There are no methods; rather, it is used just as a marker of
your intent.
• The method that needs to be implemented is inherited
from Object.
Issue With clone() method
• Finally, clone throws a CloneNotSupportedException.
• This is thrown if your class is not marked Cloneable.
• This is all a little odd but you must handle this in subclass.
Steps For Cloning
• To reiterate, if you would like objects of class C to
support cloning, do the following:
– implement the Cloneable interface
– override the clone method with public access privileges
– call super.clone()
– Handle CloneNotSupported Exception.

• This will get you default cloning means shallow
copy.
Shallow Copies With Cloning
• We haven’t yet said what the default clone()
method does.
• By default, clone makes a shallow copy of all iv’s in a
class.
• Shallow copy means that all native datatype iv’s are
copied in regular way, but iv’s that are objects are
not recursed upon – that is, references are copied.
• This is not what you typically want.
• Must override clone explicitly for Deep Copying.
Deep Copies
• For deep copies that recurse through the object iv’s,
you have to do some more work.
• super.clone() is first called to clone the first level of
iv’s.
• Returned cloned object’s object fields are then
accessed one by one and clone method is called for
each.
• See DeepClone.java example
Additional clone() properties
•

Note that the following are typical, but not strictly
required:
– x.clone() != x;
– x.clone().getClass() == x.getClass();
– x.clone().equals(x);

•

Finally, though no one really cares, Object
does not support clone();
toString() method
• The Object method
String toString();

is intended to return a readable textual representation
of the object upon which it is called. This is great for
debugging!
• Best way to think of this is using a print statement. If we
execute:
System.out.println(someObject);

we would like to see some meaningful info about
someObject, such as values of iv’s, etc.
default toString()
• By default toString() prints total garbage that no one is
interested in
getClass().getName() + '@' + Integer.toHexString(hashCode())

• By convention, print simple formatted list of field names

and values (or some important subset).
• The intent is not to overformat.
• Typically used for debugging.
• Always override toString()!
equals() method
• Recall that boolean == method compares when
applied to object compares references.
• That is, two object are the same if the point to the
same memory.
• Since java does not support operator overloading,
you cannot change this operator.
• However, the equals method of the Object class gives
you a chance to more meaningful compare objects of
a given class.
equals method, cont
• By default, equals(Object o) does exactly what
the == operator does – compare object
references.
• To override, simply override method with
version that does more meaningful test, ie
compares iv’s and returns true if equal, false
otherwise.
• See Equals.java example in course notes.
equals subtleties
• As with any method that you override, to do
so properly you must obey contracts that go
beyond interface matching.
• With equals, the extra conditions that must be
met are discussed on the next slide:
equals contract
It is reflexive: for any reference value x, x.equals(x) should
return true.
It is symmetric: for any reference values x and
y, x.equals(y) should return true if and only if y.equals(x)
returns true.
It is transitive: for any reference values x, y, and z, if
x.equals(y) returns true and y.equals(z) returns
true, then x.equals(z) should return true.
It is consistent: for any reference values x and y, multiple
invocations of x.equals(y) consistently return true or
consistently return false, provided no information used in
equals comparisons on the object is modified.
For any non-null reference value x, x.equals(null) should
return false.
hashcode() method
• Java provides all objects with the ability to
generate a hash code.
• By default, the hashing algorithm is typically
based on an integer representation of the java
address.
• This method is supported for use with
java.util.Hashtable
• Will discuss Hashtable in detail during
Collections discussion.
Rules for overriding hashcode

• Whenever invoked on the same object more than

once, the hashCode method must return the same
integer, provided no information used in equals
comparisons on the object is modified.
• If two objects are equal according to the
equals(Object) method, then calling the hashCode
method on each of the two objects must produce
the same integer result.
• It is not required that if two objects are unequal
according to the equals(java.lang.Object)
method, then calling the hashCode method on
each of the two objects must produce distinct
integer results. However, the programmer should
be aware that producing distinct integer results for
unequal objects may improve the performance of
hashtables.
finalize() method
• Called as final step when Object is no longer used,
just before garbage collection
• Object version does nothing
• Since java has automatic garbage collection, finalize()
does not need to be overridden reclaim memory.
• Can be used to reclaim other resources – close
streams, database connections, threads.
• However, it is strongly recommended not to rely on
this for scarce resources.
• Be explicit and create own dispose method.

More Related Content

PPTX
Java 103 intro to java data structures
agorolabs
 
PPT
Lesson3
Arpan91
 
PPTX
Javasession7
Rajeev Kumar
 
PPTX
Javasession6
Rajeev Kumar
 
PPTX
Autoboxing And Unboxing In Java
chathuranga kasun bamunusingha
 
PPT
Java Tutorials
Woxa Technologies
 
PPTX
Object Class
RatnaJava
 
PPTX
L9 wrapper classes
teach4uin
 
Java 103 intro to java data structures
agorolabs
 
Lesson3
Arpan91
 
Javasession7
Rajeev Kumar
 
Javasession6
Rajeev Kumar
 
Autoboxing And Unboxing In Java
chathuranga kasun bamunusingha
 
Java Tutorials
Woxa Technologies
 
Object Class
RatnaJava
 
L9 wrapper classes
teach4uin
 

What's hot (19)

PPTX
Vectors in Java
Abhilash Nair
 
DOCX
Autoboxing and unboxing
Geetha Manohar
 
PDF
Java Wrapper Classes and I/O Mechanisms
Subhadra Sundar Chakraborty
 
PPT
Core Java Concepts
mdfkhan625
 
PPT
STRINGS IN JAVA
LOVELY PROFESSIONAL UNIVERSITY
 
PPTX
Collections Training
Ramindu Deshapriya
 
PPTX
What is String in Java?
RAKESH P
 
PPTX
Presentation 4th
Connex
 
PPT
java training faridabad
Woxa Technologies
 
PPTX
OCA Java SE 8 Exam Chapter 3 Core Java APIs
İbrahim Kürce
 
PPTX
JSpiders - Wrapper classes
JSpiders Basavanagudi
 
PPTX
Java String
SATYAM SHRIVASTAV
 
ODP
Java for newcomers
Amith jayasekara
 
PPS
Wrapper class
kamal kotecha
 
PPT
Wrapper class (130240116056)
Akshay soni
 
PPTX
2CPP04 - Objects and Classes
Michael Heron
 
PPTX
Java Tutorial Lab 1
Berk Soysal
 
PPTX
2CPP13 - Operator Overloading
Michael Heron
 
PPTX
Lecture 9
talha ijaz
 
Vectors in Java
Abhilash Nair
 
Autoboxing and unboxing
Geetha Manohar
 
Java Wrapper Classes and I/O Mechanisms
Subhadra Sundar Chakraborty
 
Core Java Concepts
mdfkhan625
 
Collections Training
Ramindu Deshapriya
 
What is String in Java?
RAKESH P
 
Presentation 4th
Connex
 
java training faridabad
Woxa Technologies
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
İbrahim Kürce
 
JSpiders - Wrapper classes
JSpiders Basavanagudi
 
Java String
SATYAM SHRIVASTAV
 
Java for newcomers
Amith jayasekara
 
Wrapper class
kamal kotecha
 
Wrapper class (130240116056)
Akshay soni
 
2CPP04 - Objects and Classes
Michael Heron
 
Java Tutorial Lab 1
Berk Soysal
 
2CPP13 - Operator Overloading
Michael Heron
 
Lecture 9
talha ijaz
 
Ad

Viewers also liked (8)

DOC
Personal authentication using 3 d finger geometry (synopsis)
Mumbai Academisc
 
DOC
Computation efficient multicast key distribution(synopsis)
Mumbai Academisc
 
DOC
One to many distribution using recursive unicast trees(synopsis)
Mumbai Academisc
 
DOC
An efficient concept based mining model for enhancing text clustering(synopsis)
Mumbai Academisc
 
PDF
Engineering
Mumbai Academisc
 
DOC
Benefit based data caching in ad hoc networks (synopsis)
Mumbai Academisc
 
DOC
Mitigating performance degradation in congested sensor networks(synopsis)
Mumbai Academisc
 
PPT
Web based development
Mumbai Academisc
 
Personal authentication using 3 d finger geometry (synopsis)
Mumbai Academisc
 
Computation efficient multicast key distribution(synopsis)
Mumbai Academisc
 
One to many distribution using recursive unicast trees(synopsis)
Mumbai Academisc
 
An efficient concept based mining model for enhancing text clustering(synopsis)
Mumbai Academisc
 
Engineering
Mumbai Academisc
 
Benefit based data caching in ad hoc networks (synopsis)
Mumbai Academisc
 
Mitigating performance degradation in congested sensor networks(synopsis)
Mumbai Academisc
 
Web based development
Mumbai Academisc
 
Ad

Similar to Java tutorial part 4 (20)

PDF
CHAPTER 3 part2.pdf
FacultyAnupamaAlagan
 
PPTX
Methods common to all objects
Sandeep Chawla
 
PPTX
Joshua bloch effect java chapter 3
Kamal Mukkamala
 
PPTX
javaimplementation
FaRaz Ahmad
 
PPSX
Java.lang.object
Soham Sengupta
 
PPTX
Advanced Java - Lec #5 - Inheritance and Polymorphism.pptx
zakeraomari454
 
PPSX
Ejp 01
Md. Fasihul Kabir
 
PDF
JavaAdvanced ppt (1).pdf java advance java
VivekParmar94
 
PPT
JavaAdvanced programming for expertes dsd
meharikiros2
 
PPTX
Collections
sagsharma
 
PDF
Java Day-4
People Strategists
 
PPSX
Object Class
Hitesh-Java
 
PPTX
Some Important Methods in JAVA
SAGARDAVE29
 
PPT
Effective Java - Override clone() method judiciously
Ferdous Mahmud Shaon
 
PPTX
Session 14 - Object Class
PawanMM
 
DOCX
Core Java Equals and hash code
mhtspvtltd
 
PPTX
L03 Software Design
Ólafur Andri Ragnarsson
 
PPT
Eo gaddis java_chapter_06_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_06_Classes and Objects
Gina Bullock
 
PPT
Eo gaddis java_chapter_06_5e
Gina Bullock
 
CHAPTER 3 part2.pdf
FacultyAnupamaAlagan
 
Methods common to all objects
Sandeep Chawla
 
Joshua bloch effect java chapter 3
Kamal Mukkamala
 
javaimplementation
FaRaz Ahmad
 
Java.lang.object
Soham Sengupta
 
Advanced Java - Lec #5 - Inheritance and Polymorphism.pptx
zakeraomari454
 
JavaAdvanced ppt (1).pdf java advance java
VivekParmar94
 
JavaAdvanced programming for expertes dsd
meharikiros2
 
Collections
sagsharma
 
Java Day-4
People Strategists
 
Object Class
Hitesh-Java
 
Some Important Methods in JAVA
SAGARDAVE29
 
Effective Java - Override clone() method judiciously
Ferdous Mahmud Shaon
 
Session 14 - Object Class
PawanMM
 
Core Java Equals and hash code
mhtspvtltd
 
L03 Software Design
Ólafur Andri Ragnarsson
 
Eo gaddis java_chapter_06_5e
Gina Bullock
 
Eo gaddis java_chapter_06_Classes and Objects
Gina Bullock
 
Eo gaddis java_chapter_06_5e
Gina Bullock
 

More from Mumbai Academisc (20)

DOC
Non ieee java projects list
Mumbai Academisc
 
DOC
Non ieee dot net projects list
Mumbai Academisc
 
DOC
Ieee java projects list
Mumbai Academisc
 
DOC
Ieee 2014 java projects list
Mumbai Academisc
 
DOC
Ieee 2014 dot net projects list
Mumbai Academisc
 
DOC
Ieee 2013 java projects list
Mumbai Academisc
 
DOC
Ieee 2013 dot net projects list
Mumbai Academisc
 
DOC
Ieee 2012 dot net projects list
Mumbai Academisc
 
PPT
Spring ppt
Mumbai Academisc
 
PDF
Ejb notes
Mumbai Academisc
 
PDF
Java web programming
Mumbai Academisc
 
PDF
Java programming-examples
Mumbai Academisc
 
PPTX
Hibernate tutorial
Mumbai Academisc
 
DOCX
J2ee project lists:-Mumbai Academics
Mumbai Academisc
 
PPTX
Java tutorial part 3
Mumbai Academisc
 
PPTX
Java tutorial part 2
Mumbai Academisc
 
TXT
Project list
Mumbai Academisc
 
DOC
Predictive job scheduling in a connection limited system using parallel genet...
Mumbai Academisc
 
Non ieee java projects list
Mumbai Academisc
 
Non ieee dot net projects list
Mumbai Academisc
 
Ieee java projects list
Mumbai Academisc
 
Ieee 2014 java projects list
Mumbai Academisc
 
Ieee 2014 dot net projects list
Mumbai Academisc
 
Ieee 2013 java projects list
Mumbai Academisc
 
Ieee 2013 dot net projects list
Mumbai Academisc
 
Ieee 2012 dot net projects list
Mumbai Academisc
 
Spring ppt
Mumbai Academisc
 
Ejb notes
Mumbai Academisc
 
Java web programming
Mumbai Academisc
 
Java programming-examples
Mumbai Academisc
 
Hibernate tutorial
Mumbai Academisc
 
J2ee project lists:-Mumbai Academics
Mumbai Academisc
 
Java tutorial part 3
Mumbai Academisc
 
Java tutorial part 2
Mumbai Academisc
 
Project list
Mumbai Academisc
 
Predictive job scheduling in a connection limited system using parallel genet...
Mumbai Academisc
 

Recently uploaded (20)

PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PPTX
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
This slide provides an overview Technology
mineshkharadi333
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Software Development Company | KodekX
KodekX
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Doc9.....................................
SofiaCollazos
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Architecture of the Future (09152021)
EdwardMeyman
 
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 

Java tutorial part 4

  • 1. The Object Class • Every java class has Object as its superclass and thus inherits the Object methods. • Object is a non-abstract class • Many Object methods, however, have implementations that aren’t particularly useful in general • In most cases it is a good idea to override these methods with more useful versions. • In other cases it is required if you want your objects to correctly work with other class libraries.
  • 2. Clone Method • Recall that the “=“ operator simply copies Object references. e.g., >> Student s1 = new Student(“Smith”, Jim, 3.13); >> Student s2 = s1; >> s1.setName(“Sahil”); >> System.out.println(s2.getName()); OP:- Sahil • What if we want to actually make a copy of an Object? • Most elegant way is to use the clone() method inherited from Object. Student s2 = (Student) s1.clone();
  • 3. About clone() method • First, note that the clone method is protected in the Object class. • This means that it is protected for subclasses as well. • Hence, it cannot be called from within an Object of another class and package. • To use the clone method, you must override in your subclass and upgrade visibility to public. • Also, any class that uses clone must implement the Cloneable interface. • This is a bit different from other interfaces that we’ve seen. • There are no methods; rather, it is used just as a marker of your intent. • The method that needs to be implemented is inherited from Object.
  • 4. Issue With clone() method • Finally, clone throws a CloneNotSupportedException. • This is thrown if your class is not marked Cloneable. • This is all a little odd but you must handle this in subclass.
  • 5. Steps For Cloning • To reiterate, if you would like objects of class C to support cloning, do the following: – implement the Cloneable interface – override the clone method with public access privileges – call super.clone() – Handle CloneNotSupported Exception. • This will get you default cloning means shallow copy.
  • 6. Shallow Copies With Cloning • We haven’t yet said what the default clone() method does. • By default, clone makes a shallow copy of all iv’s in a class. • Shallow copy means that all native datatype iv’s are copied in regular way, but iv’s that are objects are not recursed upon – that is, references are copied. • This is not what you typically want. • Must override clone explicitly for Deep Copying.
  • 7. Deep Copies • For deep copies that recurse through the object iv’s, you have to do some more work. • super.clone() is first called to clone the first level of iv’s. • Returned cloned object’s object fields are then accessed one by one and clone method is called for each. • See DeepClone.java example
  • 8. Additional clone() properties • Note that the following are typical, but not strictly required: – x.clone() != x; – x.clone().getClass() == x.getClass(); – x.clone().equals(x); • Finally, though no one really cares, Object does not support clone();
  • 9. toString() method • The Object method String toString(); is intended to return a readable textual representation of the object upon which it is called. This is great for debugging! • Best way to think of this is using a print statement. If we execute: System.out.println(someObject); we would like to see some meaningful info about someObject, such as values of iv’s, etc.
  • 10. default toString() • By default toString() prints total garbage that no one is interested in getClass().getName() + '@' + Integer.toHexString(hashCode()) • By convention, print simple formatted list of field names and values (or some important subset). • The intent is not to overformat. • Typically used for debugging. • Always override toString()!
  • 11. equals() method • Recall that boolean == method compares when applied to object compares references. • That is, two object are the same if the point to the same memory. • Since java does not support operator overloading, you cannot change this operator. • However, the equals method of the Object class gives you a chance to more meaningful compare objects of a given class.
  • 12. equals method, cont • By default, equals(Object o) does exactly what the == operator does – compare object references. • To override, simply override method with version that does more meaningful test, ie compares iv’s and returns true if equal, false otherwise. • See Equals.java example in course notes.
  • 13. equals subtleties • As with any method that you override, to do so properly you must obey contracts that go beyond interface matching. • With equals, the extra conditions that must be met are discussed on the next slide:
  • 14. equals contract It is reflexive: for any reference value x, x.equals(x) should return true. It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified. For any non-null reference value x, x.equals(null) should return false.
  • 15. hashcode() method • Java provides all objects with the ability to generate a hash code. • By default, the hashing algorithm is typically based on an integer representation of the java address. • This method is supported for use with java.util.Hashtable • Will discuss Hashtable in detail during Collections discussion.
  • 16. Rules for overriding hashcode • Whenever invoked on the same object more than once, the hashCode method must return the same integer, provided no information used in equals comparisons on the object is modified. • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
  • 17. finalize() method • Called as final step when Object is no longer used, just before garbage collection • Object version does nothing • Since java has automatic garbage collection, finalize() does not need to be overridden reclaim memory. • Can be used to reclaim other resources – close streams, database connections, threads. • However, it is strongly recommended not to rely on this for scarce resources. • Be explicit and create own dispose method.