Java Universal super class java.lang.Object is discussed comprehensively with code snippets.
Also covers:
a) Why we need inheritance and dynamic method dispatch
b) Need of a universal parent
c) Delegation and proxies
d) toString(), clone(), equals(), notify()
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!