SlideShare una empresa de Scribd logo
1 de 18
java.lang.Object 
Soham 
Sengupta 
Adam-‘n’-Eve of all Java Classes 
CEO, Tech IT Easy Lab of Pervasive VM Computing 
+91 9830740684 (sohamsengupta@yahoo.com)
The father takes his little daughter 
for a stroll. Daddy’s little mermaid 
falls asleep and proud Daddy takes 
her in his arms 
Daddy daddy=new Daddy(); 
Daughter daughter=new 
Daughter(); 
daddy=daughter; 
They need to relax. 
Daddy needs a cigar to refresh. 
Little dolly does not like cigar 
Daddy decides to relax the way his 
dolly relaxes. 
daddy.realx(); 
class Daddy{ 
void realx(){ 
System.out.println("Hey !...Give me a 
Cigar"); 
} 
} 
class Daughter extends Daddy{ 
void realx(){ 
System.out.println("Uncle....Uhh..give 
me a lollypop!"); 
} 
} 
public class Main { 
public static void main(String[] 
args) { 
// TODO Auto-generated method stub 
Daddy daddy = new Daddy(); 
Daughter daughter = new Daughter(); 
daddy = daughter; 
daddy.realx(); // daddy takes 
lolly 
} 
} 
sohamsengupta@yahoo.com Monday, October 13, 2014
sohamsengupta@yahoo.com Monday, October 13, 2014 3
class Zoo{ 
static String 
listenToAnimalSound(Animal 
animal){ 
return animal.makeSound(); 
} 
static void 
feedTheAnimal(Animal animal){ 
animal.eat(); 
} 
} 
abstract class Animal{ 
abstract void eat(); 
abstract String makeSound(); 
abstract int 
getNumberOfLegs(); 
abstract boolean hasTail(); 
} 
Objective: To make a general 
concept of Animals. Now, given any 
Animal, if I have feed it, there got to 
be as many methods like the 
method, 
feedTheAnimal(AnimalCategory) as 
there are Animals in Zoo! 
So, we should go for a method, 
that accepts a general type as 
argument and obvious that it has to 
be the super type of all these 
animals in the Zoo. Call it Animal 
and that’s what we did. 
See the next page 
sohamsengupta@yahoo.com Monday, October 13, 2014 4
class Dog extends 
Animal{ 
void eat() { 
System.out.println("I 
eat everything"); 
} 
int getNumberOfLegs() { 
return 4; 
} 
boolean hasTail() { 
return true; 
} 
String makeSound() { 
sohamsengupta@yahoo.com Monday, October 13, 2014 5 
return "BARK"; 
} 
} 
class Cow extends 
Animal{ 
void eat() { 
System.out.println("I am 
herbivorous."); 
} 
int getNumberOfLegs() { 
return 4; 
} 
boolean hasTail() { 
return true; 
} 
String makeSound() { 
return "MOW!"; 
} 
}
public class Main1 { 
public static void main(String[] args) { 
// TODO Auto-generated method stub 
Animal animalIViewNow=new Dog(); 
Zoo.feedTheAnimal(animalIViewNow); 
animalIViewNow=new Cow(); 
Zoo.feedTheAnimal(animalIViewNow); 
sohamsengupta@yahoo.com Monday, October 13, 2014 6 
} 
}
Case-1 
We have a method 
in a class that 
returns an object of 
any class which is 
not predictable or 
not restricted to 
existing JRE 
libraries. 
The method must 
return the Daddy 
and treat his child. 
class Zoo1{ 
public static Animal 
recAnmBySnd(String 
soundAnimalMakes){ 
// some look up logic 
return animalFound; 
} 
} 
sohamsengupta@yahoo.com Monday, October 13, 2014 7
Case-1 (Continued) 
Now if we have a method 
which returns an object of any 
class, then how do we know 
which class must be on the top 
of all? 
Here java.lang.Object comes in 
the scene. 
This is the universal super class 
Interfaces do not inherit from 
this class, but the classes that 
implement them do! 
Case-2 
Also, if we have a method that 
accepts an object of any 
class, we make the method 
accept an object of type 
java.lang.Object 
void getInfo(Object obj){ 
} 
sohamsengupta@yahoo.com Monday, October 13, 2014 8
public boolean equals(Object 
obj) 
public String toString() 
public Object clone() throws 
CloneNotSuppotedException 
protected void finalize() 
throws Throwable 
public native int hashCode() 
public Class getClass() 
Some more methods 
involved with thread 
activities collaboration 
wait() and its overloaded 
version 
notify(), notifyAll() 
All these methods got to be 
part of each class and 
hence were introduced in 
the universal super class 
following the need 
originating from Inheritiance 
sohamsengupta@yahoo.com Monday, October 13, 2014 9
sohamsengupta@yahoo.com Monday, October 13, 2014 10 
class MyClass{ 
} 
public class Main1 { 
public static void 
main(String[] args) { 
MyClass obj=new MyClass(); 
System.out.println(obj.toStri 
ng()); 
} 
} 
Output:MyClass@addbf1 
class MyClass{ 
public String String(){ 
return "I am here"; 
} 
} 
public class Main1 { 
public static void 
main(String[] args) { 
MyClass obj=new 
MyClass(); 
System.out.println(obj.to 
String()); 
} 
} 
Output:I am here
sohamsengupta@yahoo.com Monday, October 13, 2014 11 
class MyClass { 
} 
public class Main1 { 
public static void main(String[] args) { 
MyClass obj1 = new MyClass(); 
MyClass obj2 = new MyClass(); 
System.out.println("obj1==obj2 : " + (obj1 == obj2)); 
MyClass obj3 = obj1; 
System.out.println("obj1==obj3 : " + (obj1 == obj3)); 
//=========================== 
System.out.println("obj1.equals(obj2) " + obj1.equals(obj2)); 
System.out.println("obj1.equals(obj3) " + obj1.equals(obj3)); 
} 
} 
This method returns, by default, 
unless overridden otherwise, the 
equivalent of objRef1==objRef2
class Height{ 
int inch; 
int feet; 
public Height(int 
inch, int feet) { 
super(); 
this.inch = inch; 
this.feet = feet; 
} 
} public boolean equals(Object obj) 
If we need to compare two 
objects of same class, on some 
custom constraint, suppose two 
objects of the class on our right, 
Height, should be considered 
to equal each other if the fields 
are equal, we override as,: 
{ 
if(obj instanceof Height==false){ 
throw new 
IllegalArgumentException("Can 
compare only same objects"); 
} 
Height objHeight=(Height)obj; 
return this.feet==objHeight.feet 
&& this.inch==objHeight.inch; 
} 
sohamsengupta@yahoo.com Monday, October 13, 2014 12
class MyClass{ 
String s; 
public MyClass(String s) { 
this.s = s; 
} 
public void finalize() 
throws Throwable { 
cleanupAllResources(); // 
The method that cleans up 
} 
private void 
cleanupAllResources() { 
// do some relavant task 
System.out.println("I am 
dying.... : says "+s); 
} 
} 
This method is overridden to 
free up extra resources when 
they are no longer in use and 
subject to Garbage 
Collection once the object is 
eligible to be swallowed up 
by the garbage collector 
This works very much like the 
destructors in C++ 
These methods is only for 
system purpose and 
optimization and its 
execution is subject to GC, 
depending on the VM and 
platform and Execution 
Environment and timeline 
sohamsengupta@yahoo.com Monday, October 13, 2014 13
sohamsengupta@yahoo.com Monday, October 13, 2014 14 
class MC { 
int marks; 
String name; 
public MC(int marks, String 
name) { 
super(); 
this.marks = marks; 
this.name = name; 
} 
void show() { 
System.out.println(name + " 
scored " + marks); 
} 
void setMarks(int marks) { 
this.marks = marks; 
} 
} 
class Main { 
public static void 
main(String[] args) { 
MC mc1=new MC(94,"Soham"); 
mc1.show(); // as usual 
MC mc2 = mc1; 
mc2.show(); // mc2 a copy 
//of mc1 
mc2.setMarks(880);// change 
mc2.show();// mc2 changed 
mc1.show(); // mc1 also! 
} 
} 
So, it is very risky to create a 
duplicate/clone by reference of 
the source. Because, the change 
in the clone affects the source!
class MC implements Cloneable { 
int marks; 
String name; 
public MC(int marks, String name) { 
super(); 
this.marks = marks; 
this.name = name; 
} 
void show() { 
System.out.println(name + " scored " + 
marks); 
} 
void setMarks(int marks) { 
this.marks = marks; 
} 
@Override 
protected Object clone() throws 
CloneNotSupportedException { 
return super.clone(); 
} 
} 
Cloneable 
 It must override the clone() 
method and return a super type 
implementation of the method 
 Notice the checked exception, 
CloneNotSupportedException, 
that the method declares to 
throw 
 If a class does not implement the 
Cloneable interface, this 
exception is thrown 
 It’s very much like the birth control 
mechanism, of objects! 
sohamsengupta@yahoo.com Monday, October 13, 2014 15
class MC implements Cloneable { 
int[] marks; 
String name; 
public MC(int[] marks, String name) { 
super(); 
this.marks = marks; 
this.name = name; 
} 
void show() { 
System.out.println("Score of " + name + “…n"); 
String[] exams = { "10th", "12th", "B.Tech" }; 
for (int i = 0; i < marks.length; i++) { 
System.out.println(exams[i] + "===>" +marks[i]); 
} 
System.out.println("********"); 
} 
void setMarks(int i, int newMarks) { 
this.marks[i] = newMarks; 
} 
@Override 
protected Object clone() throws 
CloneNotSupportedException { 
return super.clone(); 
} 
} 
sohamsengupta@yahoo.com Monday, October 13, 2014 16 
But is it foolproof? 
Let me try the 
code on the right… 
What I get is…!!!! 
Looo! 
This has no luck! The 
source is affected, if it 
has some of its fields as 
reference type, like int[] 
here. So?
class MC implements Cloneable { 
int[] marks; 
String name; 
public MC(int[] marks, String name) { 
super(); 
this.marks = marks; 
this.name = name; 
} 
void show() { 
System.out.println("Score of " + name + "... 
n"); 
String[] exams = { "10th", "12th", "B.Tech" }; 
for (int i = 0; i < marks.length; i++) { 
System.out.println(exams[i] +"==>" +marks[i]); 
} 
System.out.println("********"); 
} 
void setMarks(int i, int newMarks) { 
this.marks[i] = newMarks; 
} 
@Override 
protected Object clone() throws 
CloneNotSupportedException { 
MC mc=(MC)super.clone(); 
mc.marks=(int[])this.marks.clone(); 
return mc; 
} 
} 
sohamsengupta@yahoo.com Monday, October 13, 2014 17 
Wow! I made this 
work 
It is done as shown 
on the right. This is 
known as Depth 
cloning and the 
former “Shallow 
cloning”… Hope 
you enjoyed!
sohamsengupta@yahoo.com Monday, October 13, 2014 18

Más contenido relacionado

La actualidad más candente

33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
Codecamp Romania
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
mikaelbarbero
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
Mite Mitreski
 

La actualidad más candente (20)

Google guava
Google guavaGoogle guava
Google guava
 
Akka
AkkaAkka
Akka
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
Testing a 2D Platformer with Spock
Testing a 2D Platformer with SpockTesting a 2D Platformer with Spock
Testing a 2D Platformer with Spock
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
20071201 Eliminare For @JavaDayRoma2 Roma-IT [ITA]
20071201 Eliminare For @JavaDayRoma2 Roma-IT [ITA]20071201 Eliminare For @JavaDayRoma2 Roma-IT [ITA]
20071201 Eliminare For @JavaDayRoma2 Roma-IT [ITA]
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To Test
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Taking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with SourceryTaking the boilerplate out of your tests with Sourcery
Taking the boilerplate out of your tests with Sourcery
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
Java practical
Java practicalJava practical
Java practical
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Kotlin: a better Java
Kotlin: a better JavaKotlin: a better Java
Kotlin: a better Java
 

Similar a Java.lang.object

About java
About javaAbout java
About java
Jay Xu
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
HamletDRC
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
adityaraj7711
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdf
NicholasflqStewartl
 

Similar a Java.lang.object (20)

About java
About javaAbout java
About java
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Java programs
Java programsJava programs
Java programs
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdf
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
OOP Lab Report.docx
OOP Lab Report.docxOOP Lab Report.docx
OOP Lab Report.docx
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 

Más de Soham Sengupta

Más de Soham Sengupta (20)

Spring method-level-secuirty
Spring method-level-secuirtySpring method-level-secuirty
Spring method-level-secuirty
 
Spring security mvc-1
Spring security mvc-1Spring security mvc-1
Spring security mvc-1
 
JavaScript event handling assignment
JavaScript  event handling assignment JavaScript  event handling assignment
JavaScript event handling assignment
 
Networking assignment 2
Networking assignment 2Networking assignment 2
Networking assignment 2
 
Networking assignment 1
Networking assignment 1Networking assignment 1
Networking assignment 1
 
Sohams cryptography basics
Sohams cryptography basicsSohams cryptography basics
Sohams cryptography basics
 
Network programming1
Network programming1Network programming1
Network programming1
 
JSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorialJSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorial
 
Xmpp and java
Xmpp and javaXmpp and java
Xmpp and java
 
Core java day2
Core java day2Core java day2
Core java day2
 
Core java day1
Core java day1Core java day1
Core java day1
 
Core java day4
Core java day4Core java day4
Core java day4
 
Core java day5
Core java day5Core java day5
Core java day5
 
Exceptions
ExceptionsExceptions
Exceptions
 
Jsp1
Jsp1Jsp1
Jsp1
 
Soham web security
Soham web securitySoham web security
Soham web security
 
Html tables and_javascript
Html tables and_javascriptHtml tables and_javascript
Html tables and_javascript
 
Html javascript
Html javascriptHtml javascript
Html javascript
 
Java script
Java scriptJava script
Java script
 
Sohamsg ajax
Sohamsg ajaxSohamsg ajax
Sohamsg ajax
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 

Último (20)

Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

Java.lang.object

  • 1. java.lang.Object Soham Sengupta Adam-‘n’-Eve of all Java Classes CEO, Tech IT Easy Lab of Pervasive VM Computing +91 9830740684 (sohamsengupta@yahoo.com)
  • 2. The father takes his little daughter for a stroll. Daddy’s little mermaid falls asleep and proud Daddy takes her in his arms Daddy daddy=new Daddy(); Daughter daughter=new Daughter(); daddy=daughter; They need to relax. Daddy needs a cigar to refresh. Little dolly does not like cigar Daddy decides to relax the way his dolly relaxes. daddy.realx(); class Daddy{ void realx(){ System.out.println("Hey !...Give me a Cigar"); } } class Daughter extends Daddy{ void realx(){ System.out.println("Uncle....Uhh..give me a lollypop!"); } } public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Daddy daddy = new Daddy(); Daughter daughter = new Daughter(); daddy = daughter; daddy.realx(); // daddy takes lolly } } sohamsengupta@yahoo.com Monday, October 13, 2014
  • 4. class Zoo{ static String listenToAnimalSound(Animal animal){ return animal.makeSound(); } static void feedTheAnimal(Animal animal){ animal.eat(); } } abstract class Animal{ abstract void eat(); abstract String makeSound(); abstract int getNumberOfLegs(); abstract boolean hasTail(); } Objective: To make a general concept of Animals. Now, given any Animal, if I have feed it, there got to be as many methods like the method, feedTheAnimal(AnimalCategory) as there are Animals in Zoo! So, we should go for a method, that accepts a general type as argument and obvious that it has to be the super type of all these animals in the Zoo. Call it Animal and that’s what we did. See the next page sohamsengupta@yahoo.com Monday, October 13, 2014 4
  • 5. class Dog extends Animal{ void eat() { System.out.println("I eat everything"); } int getNumberOfLegs() { return 4; } boolean hasTail() { return true; } String makeSound() { sohamsengupta@yahoo.com Monday, October 13, 2014 5 return "BARK"; } } class Cow extends Animal{ void eat() { System.out.println("I am herbivorous."); } int getNumberOfLegs() { return 4; } boolean hasTail() { return true; } String makeSound() { return "MOW!"; } }
  • 6. public class Main1 { public static void main(String[] args) { // TODO Auto-generated method stub Animal animalIViewNow=new Dog(); Zoo.feedTheAnimal(animalIViewNow); animalIViewNow=new Cow(); Zoo.feedTheAnimal(animalIViewNow); sohamsengupta@yahoo.com Monday, October 13, 2014 6 } }
  • 7. Case-1 We have a method in a class that returns an object of any class which is not predictable or not restricted to existing JRE libraries. The method must return the Daddy and treat his child. class Zoo1{ public static Animal recAnmBySnd(String soundAnimalMakes){ // some look up logic return animalFound; } } sohamsengupta@yahoo.com Monday, October 13, 2014 7
  • 8. Case-1 (Continued) Now if we have a method which returns an object of any class, then how do we know which class must be on the top of all? Here java.lang.Object comes in the scene. This is the universal super class Interfaces do not inherit from this class, but the classes that implement them do! Case-2 Also, if we have a method that accepts an object of any class, we make the method accept an object of type java.lang.Object void getInfo(Object obj){ } sohamsengupta@yahoo.com Monday, October 13, 2014 8
  • 9. public boolean equals(Object obj) public String toString() public Object clone() throws CloneNotSuppotedException protected void finalize() throws Throwable public native int hashCode() public Class getClass() Some more methods involved with thread activities collaboration wait() and its overloaded version notify(), notifyAll() All these methods got to be part of each class and hence were introduced in the universal super class following the need originating from Inheritiance sohamsengupta@yahoo.com Monday, October 13, 2014 9
  • 10. sohamsengupta@yahoo.com Monday, October 13, 2014 10 class MyClass{ } public class Main1 { public static void main(String[] args) { MyClass obj=new MyClass(); System.out.println(obj.toStri ng()); } } Output:MyClass@addbf1 class MyClass{ public String String(){ return "I am here"; } } public class Main1 { public static void main(String[] args) { MyClass obj=new MyClass(); System.out.println(obj.to String()); } } Output:I am here
  • 11. sohamsengupta@yahoo.com Monday, October 13, 2014 11 class MyClass { } public class Main1 { public static void main(String[] args) { MyClass obj1 = new MyClass(); MyClass obj2 = new MyClass(); System.out.println("obj1==obj2 : " + (obj1 == obj2)); MyClass obj3 = obj1; System.out.println("obj1==obj3 : " + (obj1 == obj3)); //=========================== System.out.println("obj1.equals(obj2) " + obj1.equals(obj2)); System.out.println("obj1.equals(obj3) " + obj1.equals(obj3)); } } This method returns, by default, unless overridden otherwise, the equivalent of objRef1==objRef2
  • 12. class Height{ int inch; int feet; public Height(int inch, int feet) { super(); this.inch = inch; this.feet = feet; } } public boolean equals(Object obj) If we need to compare two objects of same class, on some custom constraint, suppose two objects of the class on our right, Height, should be considered to equal each other if the fields are equal, we override as,: { if(obj instanceof Height==false){ throw new IllegalArgumentException("Can compare only same objects"); } Height objHeight=(Height)obj; return this.feet==objHeight.feet && this.inch==objHeight.inch; } sohamsengupta@yahoo.com Monday, October 13, 2014 12
  • 13. class MyClass{ String s; public MyClass(String s) { this.s = s; } public void finalize() throws Throwable { cleanupAllResources(); // The method that cleans up } private void cleanupAllResources() { // do some relavant task System.out.println("I am dying.... : says "+s); } } This method is overridden to free up extra resources when they are no longer in use and subject to Garbage Collection once the object is eligible to be swallowed up by the garbage collector This works very much like the destructors in C++ These methods is only for system purpose and optimization and its execution is subject to GC, depending on the VM and platform and Execution Environment and timeline sohamsengupta@yahoo.com Monday, October 13, 2014 13
  • 14. sohamsengupta@yahoo.com Monday, October 13, 2014 14 class MC { int marks; String name; public MC(int marks, String name) { super(); this.marks = marks; this.name = name; } void show() { System.out.println(name + " scored " + marks); } void setMarks(int marks) { this.marks = marks; } } class Main { public static void main(String[] args) { MC mc1=new MC(94,"Soham"); mc1.show(); // as usual MC mc2 = mc1; mc2.show(); // mc2 a copy //of mc1 mc2.setMarks(880);// change mc2.show();// mc2 changed mc1.show(); // mc1 also! } } So, it is very risky to create a duplicate/clone by reference of the source. Because, the change in the clone affects the source!
  • 15. class MC implements Cloneable { int marks; String name; public MC(int marks, String name) { super(); this.marks = marks; this.name = name; } void show() { System.out.println(name + " scored " + marks); } void setMarks(int marks) { this.marks = marks; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } Cloneable  It must override the clone() method and return a super type implementation of the method  Notice the checked exception, CloneNotSupportedException, that the method declares to throw  If a class does not implement the Cloneable interface, this exception is thrown  It’s very much like the birth control mechanism, of objects! sohamsengupta@yahoo.com Monday, October 13, 2014 15
  • 16. class MC implements Cloneable { int[] marks; String name; public MC(int[] marks, String name) { super(); this.marks = marks; this.name = name; } void show() { System.out.println("Score of " + name + “…n"); String[] exams = { "10th", "12th", "B.Tech" }; for (int i = 0; i < marks.length; i++) { System.out.println(exams[i] + "===>" +marks[i]); } System.out.println("********"); } void setMarks(int i, int newMarks) { this.marks[i] = newMarks; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } sohamsengupta@yahoo.com Monday, October 13, 2014 16 But is it foolproof? Let me try the code on the right… What I get is…!!!! Looo! This has no luck! The source is affected, if it has some of its fields as reference type, like int[] here. So?
  • 17. class MC implements Cloneable { int[] marks; String name; public MC(int[] marks, String name) { super(); this.marks = marks; this.name = name; } void show() { System.out.println("Score of " + name + "... n"); String[] exams = { "10th", "12th", "B.Tech" }; for (int i = 0; i < marks.length; i++) { System.out.println(exams[i] +"==>" +marks[i]); } System.out.println("********"); } void setMarks(int i, int newMarks) { this.marks[i] = newMarks; } @Override protected Object clone() throws CloneNotSupportedException { MC mc=(MC)super.clone(); mc.marks=(int[])this.marks.clone(); return mc; } } sohamsengupta@yahoo.com Monday, October 13, 2014 17 Wow! I made this work It is done as shown on the right. This is known as Depth cloning and the former “Shallow cloning”… Hope you enjoyed!