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

More Related Content

PPTX
Java 8 Puzzlers [as presented at OSCON 2016]
PPTX
The Groovy Puzzlers – The Complete 01 and 02 Seasons
PDF
Sam wd programs
PPT
Learning Java 1 – Introduction
PDF
Important java programs(collection+file)
PDF
Kotlin Generation
PPT
2012 JDays Bad Tests Good Tests
KEY
Djangocon11: Monkeying around at New Relic
Java 8 Puzzlers [as presented at OSCON 2016]
The Groovy Puzzlers – The Complete 01 and 02 Seasons
Sam wd programs
Learning Java 1 – Introduction
Important java programs(collection+file)
Kotlin Generation
2012 JDays Bad Tests Good Tests
Djangocon11: Monkeying around at New Relic

What's hot (20)

PDF
Google guava
ODP
PDF
33rd Degree 2013, Bad Tests, Good Tests
PPTX
CodeCamp Iasi 10 march 2012 - Practical Groovy
PDF
Testing a 2D Platformer with Spock
PDF
Java Concurrency by Example
PDF
20071201 Eliminare For @JavaDayRoma2 Roma-IT [ITA]
PDF
Spock: A Highly Logical Way To Test
PPTX
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
KEY
Clojure Intro
PDF
Taking the boilerplate out of your tests with Sourcery
PDF
Advanced Java Practical File
PDF
Google Guava & EMF @ GTUG Nantes
PPT
final year project center in Coimbatore
PDF
Clojure for Java developers
PDF
DCN Practical
DOCX
Java practical
PDF
The core libraries you always wanted - Google Guava
PDF
Core java pract_sem iii
PDF
Kotlin: a better Java
Google guava
33rd Degree 2013, Bad Tests, Good Tests
CodeCamp Iasi 10 march 2012 - Practical Groovy
Testing a 2D Platformer with Spock
Java Concurrency by Example
20071201 Eliminare For @JavaDayRoma2 Roma-IT [ITA]
Spock: A Highly Logical Way To Test
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Clojure Intro
Taking the boilerplate out of your tests with Sourcery
Advanced Java Practical File
Google Guava & EMF @ GTUG Nantes
final year project center in Coimbatore
Clojure for Java developers
DCN Practical
Java practical
The core libraries you always wanted - Google Guava
Core java pract_sem iii
Kotlin: a better Java
Ad

Similar to Java.lang.object (20)

KEY
About java
PPTX
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
PDF
The Future of JVM Languages
PPTX
Detailed_description_on_java_ppt_final.pptx
ODP
AST Transformations at JFokus
PDF
Java programs
PDF
What can be done with Java, but should better be done with Erlang (@pavlobaron)
PPTX
Chap2 class,objects contd
PPTX
Programing with java for begniers .pptx
PDF
Java Class Design
PDF
Having a problem figuring out where my errors are- The code is not run.pdf
PPTX
Exception Handling
DOCX
Autoboxing and unboxing
PPTX
Nantes Jug - Java 7
DOCX
OOP Lab Report.docx
PPTX
131 Lab slides (all in one)
PPTX
A topology of memory leaks on the JVM
PPTX
OBJECT ORIENTED PROGRAMMING STRUCU2.pptx
PDF
Lezione03
PDF
Lezione03
About java
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
The Future of JVM Languages
Detailed_description_on_java_ppt_final.pptx
AST Transformations at JFokus
Java programs
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Chap2 class,objects contd
Programing with java for begniers .pptx
Java Class Design
Having a problem figuring out where my errors are- The code is not run.pdf
Exception Handling
Autoboxing and unboxing
Nantes Jug - Java 7
OOP Lab Report.docx
131 Lab slides (all in one)
A topology of memory leaks on the JVM
OBJECT ORIENTED PROGRAMMING STRUCU2.pptx
Lezione03
Lezione03
Ad

More from Soham Sengupta (20)

PPTX
Spring method-level-secuirty
PPTX
Spring security mvc-1
PDF
JavaScript event handling assignment
PDF
Networking assignment 2
PDF
Networking assignment 1
PPT
Sohams cryptography basics
PPT
Network programming1
PPT
JSR-82 Bluetooth tutorial
PPSX
Xmpp and java
PPT
Core java day2
PPT
Core java day1
PPT
Core java day4
PPT
Core java day5
PPT
Exceptions
PPTX
Soham web security
PPTX
Html tables and_javascript
PPT
Html javascript
PPT
Java script
PPS
Sohamsg ajax
Spring method-level-secuirty
Spring security mvc-1
JavaScript event handling assignment
Networking assignment 2
Networking assignment 1
Sohams cryptography basics
Network programming1
JSR-82 Bluetooth tutorial
Xmpp and java
Core java day2
Core java day1
Core java day4
Core java day5
Exceptions
Soham web security
Html tables and_javascript
Html javascript
Java script
Sohamsg ajax

Recently uploaded (20)

PDF
Nekopoi APK 2025 free lastest update
PPTX
Oracle Fusion HCM Cloud Demo for Beginners
PDF
Autodesk AutoCAD Crack Free Download 2025
PPTX
Monitoring Stack: Grafana, Loki & Promtail
PDF
medical staffing services at VALiNTRY
PDF
Salesforce Agentforce AI Implementation.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
iTop VPN 6.5.0 Crack + License Key 2025 (Premium Version)
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Cost to Outsource Software Development in 2025
PDF
Designing Intelligence for the Shop Floor.pdf
Nekopoi APK 2025 free lastest update
Oracle Fusion HCM Cloud Demo for Beginners
Autodesk AutoCAD Crack Free Download 2025
Monitoring Stack: Grafana, Loki & Promtail
medical staffing services at VALiNTRY
Salesforce Agentforce AI Implementation.pdf
Wondershare Filmora 15 Crack With Activation Key [2025
Navsoft: AI-Powered Business Solutions & Custom Software Development
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Operating system designcfffgfgggggggvggggggggg
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Computer Software and OS of computer science of grade 11.pptx
iTop VPN 6.5.0 Crack + License Key 2025 (Premium Version)
Design an Analysis of Algorithms I-SECS-1021-03
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Odoo Companies in India – Driving Business Transformation.pdf
Cost to Outsource Software Development in 2025
Designing Intelligence for the Shop Floor.pdf

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 ([email protected])
  • 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 } } [email protected] 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 [email protected] 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() { [email protected] 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); [email protected] 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; } } [email protected] 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){ } [email protected] 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 [email protected] Monday, October 13, 2014 9
  • 10. [email protected] 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. [email protected] 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; } [email protected] 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 [email protected] Monday, October 13, 2014 13
  • 14. [email protected] 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! [email protected] 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(); } } [email protected] 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; } } [email protected] 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!