SlideShare une entreprise Scribd logo
1  sur  17
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.

Contenu connexe

Tendances (20)

Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Finalize() method
Finalize() methodFinalize() method
Finalize() method
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
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
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
 
JSpiders - Wrapper classes
JSpiders - Wrapper classesJSpiders - Wrapper classes
JSpiders - Wrapper classes
 
Java String
Java String Java String
Java String
 
Java for newcomers
Java for newcomersJava for newcomers
Java for newcomers
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Wrapper class (130240116056)
Wrapper class (130240116056)Wrapper class (130240116056)
Wrapper class (130240116056)
 
2CPP04 - Objects and Classes
2CPP04 - Objects and Classes2CPP04 - Objects and Classes
2CPP04 - Objects and Classes
 
Java Tutorial Lab 1
Java Tutorial Lab 1Java Tutorial Lab 1
Java Tutorial Lab 1
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 

En vedette

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

En vedette (8)

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

Similaire à Java tutorial part 4

Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3Kamal Mukkamala
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxethiouniverse
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On WorkshopArpit Poladia
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptxSAICHARANREDDYN
 
Никита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CНикита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CDataArt
 
Java Collection
Java CollectionJava Collection
Java CollectionDeeptiJava
 
Ios development
Ios developmentIos development
Ios developmentelnaqah
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Christopher Haupt
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object ClassPawanMM
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 

Similaire à Java tutorial part 4 (20)

Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptx
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
 
Lesson3
Lesson3Lesson3
Lesson3
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
 
Никита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CНикита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-C
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Java Collection
Java CollectionJava Collection
Java Collection
 
ppt_on_java.pptx
ppt_on_java.pptxppt_on_java.pptx
ppt_on_java.pptx
 
Ios development
Ios developmentIos development
Ios development
 
Object concepts
Object conceptsObject concepts
Object concepts
 
Object Class
Object Class Object Class
Object Class
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object Class
 
About Python
About PythonAbout Python
About Python
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Object concepts
Object conceptsObject concepts
Object concepts
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 

Plus de Mumbai Academisc

Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list Mumbai Academisc
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list Mumbai Academisc
 
Ieee 2014 java projects list
Ieee 2014 java projects list Ieee 2014 java projects list
Ieee 2014 java projects list Mumbai Academisc
 
Ieee 2014 dot net projects list
Ieee 2014 dot net projects list Ieee 2014 dot net projects list
Ieee 2014 dot net projects list Mumbai Academisc
 
Ieee 2013 java projects list
Ieee 2013 java projects list Ieee 2013 java projects list
Ieee 2013 java projects list Mumbai Academisc
 
Ieee 2013 dot net projects list
Ieee 2013 dot net projects listIeee 2013 dot net projects list
Ieee 2013 dot net projects listMumbai Academisc
 
Ieee 2012 dot net projects list
Ieee 2012 dot net projects listIeee 2012 dot net projects list
Ieee 2012 dot net projects listMumbai Academisc
 
J2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai AcademicsJ2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai AcademicsMumbai Academisc
 
Predictive job scheduling in a connection limited system using parallel genet...
Predictive job scheduling in a connection limited system using parallel genet...Predictive job scheduling in a connection limited system using parallel genet...
Predictive job scheduling in a connection limited system using parallel genet...Mumbai Academisc
 
Performance of a speculative transmission scheme for scheduling latency reduc...
Performance of a speculative transmission scheme for scheduling latency reduc...Performance of a speculative transmission scheme for scheduling latency reduc...
Performance of a speculative transmission scheme for scheduling latency reduc...Mumbai Academisc
 

Plus de Mumbai Academisc (20)

Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
Ieee java projects list
Ieee java projects list Ieee java projects list
Ieee java projects list
 
Ieee 2014 java projects list
Ieee 2014 java projects list Ieee 2014 java projects list
Ieee 2014 java projects list
 
Ieee 2014 dot net projects list
Ieee 2014 dot net projects list Ieee 2014 dot net projects list
Ieee 2014 dot net projects list
 
Ieee 2013 java projects list
Ieee 2013 java projects list Ieee 2013 java projects list
Ieee 2013 java projects list
 
Ieee 2013 dot net projects list
Ieee 2013 dot net projects listIeee 2013 dot net projects list
Ieee 2013 dot net projects list
 
Ieee 2012 dot net projects list
Ieee 2012 dot net projects listIeee 2012 dot net projects list
Ieee 2012 dot net projects list
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
J2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai AcademicsJ2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai Academics
 
Jdbc
JdbcJdbc
Jdbc
 
Java tutorial part 2
Java tutorial part 2Java tutorial part 2
Java tutorial part 2
 
Jsp
JspJsp
Jsp
 
Project list
Project listProject list
Project list
 
Predictive job scheduling in a connection limited system using parallel genet...
Predictive job scheduling in a connection limited system using parallel genet...Predictive job scheduling in a connection limited system using parallel genet...
Predictive job scheduling in a connection limited system using parallel genet...
 
Performance of a speculative transmission scheme for scheduling latency reduc...
Performance of a speculative transmission scheme for scheduling latency reduc...Performance of a speculative transmission scheme for scheduling latency reduc...
Performance of a speculative transmission scheme for scheduling latency reduc...
 

Dernier

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 

Dernier (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

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.