Sie sind auf Seite 1von 20

Dynamic Binding or Late Binding

Dynamic Binding refers to the case where compiler is not able to


resolve the call and the binding is done at runtime only.
• Let's try to understand this. Suppose we have a class named
'SuperClass' and another class named 'SubClass' extends it.
• Now a 'SuperClass' reference can be assigned to an object of the
type 'SubClass' as well.
If we have a method (say 'someMethod()') in the 'SuperClass' which
we override in the 'SubClass' then a call of that method on a
'SuperClass' reference can only be resolved at runtime as the compiler
can't be sure of what type of object this reference would be pointing to
at runtime.

...
SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();
...

superClass1.someMethod(); // SuperClass version is called


superClass2.someMethod(); // SubClass version is called
....

Here, we see that even though both the object


references superClass1 andsuperClass2 are of type 'SuperClass' only,
but at run time they refer to the objects of types 'SuperClass' and
'SubClass' respectively.

Hence, at compile time the compiler can't be sure if the call to the
method 'someMethod()' on these references actually refer to which
version of the method - the super class version or the sub class
version.

Thus, we see that dynamic binding in Java simply binds the method
calls (inherited methods only as they can be overriden in a sub class
and hence compiler may not be sure of which version of the method to
call) based on the actual object type and not on the declared type of
the object reference.

The Object Class

• The Object class sits at the top of the class hierarchy tree in
the Java development environment.
• Every class in the Java system is a descendent (direct or
indirect) of the Object class.
• The Object class defines the basic state and behavior that all
objects must have, such as the ability to compare oneself to
another object, to convert to a string, to wait on a condition
variable, to notify other objects that a condition variable has
changed, and to return the object's class.

The equals Method


• Use the equals to compare two objects for equality. This
method returns true if the objects are equal, false otherwise.
• Note that equality does not mean that the objects are the same
object.
• Consider this code that tests
two Integers, one and anotherOne, for equality:
Integer one = new Integer(1), anotherOne = new Integer(1);

if (one.equals(anotherOne))
System.out.println("objects are equal");
This code will display objects are equal even
though one and anotherOne reference two different, distinct objects.
They are considered equal because they contain the same integer
value.

• Your classes should override this method to provide an


appropriate equality test. Your equals method should compare
the contents of the objects to see if they are functionally equal
and return true if they are.

The getClass Method


• The getClass method is a final method (cannot be overridden)
that returns a runtime representation of the class of this object.
• This method returns a Class object.
• You can query the Class object for a variety of information
about the class, such as its name, its superclass, and the
names of the interfaces that it implements.

The following method gets and displays the class name of an object:

void PrintClassName(Object obj)


{
System.out.println("The Object's class is " +
obj.getClass().getName());
}

One handy use of the getClass method is to create a new instance of


a class without knowing what the class is at compile time. This
sample method creates a new instance of the same class
as obj which can be any class that inherits from Object (which means
that it could be any class):
Object createNewInstanceOf(Object obj) {
return obj.getClass().newInstance();
}

The toString Method


• Object's toString method returns a String representation of the
object. You can use toString to display an object.
• For example, you could display a String representation of the
current Thread like this:
System.out.println(Thread.currentThread().toString());
• The String representation for an object is entirely dependent on
the object.
• The String representation of an Integer object is the integer
value displayed as text.
• The String representation of a Thread object contains various
attributes about the thread, such as its name and priority. For
example, the previous of code above display the following:
• Thread[main,5,main]
• The toString method is very useful for debugging and it would
behoove you to override this method in all your classes.
Object cloning
• When a copy of a variable is made, the original and the copy
objects have references to the same object.
• This means a change to either variable also affects the other

Employee original=new Employee (“John Public”, 50000);


Employee copy=original;
Copy. raise
Salary(10);//original objects salary also changed

Copying

Original=

Copy= Employee

• In order to copy an old object into another new object which should
not refer to the old object but the values has to be copied to a new
reference then use the clone method

Employee copy=original.clone();
Copy.raiseSalary(10);//OK—original unchanged

• The clone method is protected method of object. Only the Employee


class can clone Employee objects. there are two types of cloning,
they are
1. Shallow cloning-(default cloning method)
2. Deep cloning
• For every class, need to decide to decide weather
1. The default clone method (shallow clone) is enough;
2. the default cloe method can be patched up by calling clone on the
mutable subobjects(Deep clone)

• To do cloning, a class must


1.Implemennt the cloneable interface;and
2.Redefine the clone method with the public access modifier
Cloning
Original=

employee

Copy=

employee

Shallow Cloning
• Shallow cloning means field by field copying.
• If each and every field is numbered or basic types their is no
problem.
• If the fields in turn are objects of another class, then field by field
copying will make the original and copy objects to refer to the same
sub-objects.
• This happens because the object class has no information about the
fields of the class which calls the clone method.
• If the subobject that is shared between the original and the shallow
clone is immunable, then the sharing is safe.
• This certainly happens if the subobjects belong to an immunable
class, such as string, otherwise the subobject may simply remain
constant throughout the lifetime of the object (no method changing
the value or yielding a reference)
• Consider the Employee class with fields’ name, salary and
hireday.the shallow copy is shown

Copying

Employee
Original= name
string
salary

hireDay

Employee
Copy=
name date
salary
hireDay

• But mostly the sub objects are mutable. So must go for deep copy.
• In the above example,the hireDay field is an object of Date class
which is a mutable class.
• An example-Employee class with two fields-name and salary.
• As hireDay is a mutable object, will be included when talking about
deep cloning

public class Employee implements Cloneable


{
public Employee(String n,double S)
{
Salary=s;
Name=n;
}
public void raiseSalary(int percent)
{
This.salary=salary+salary*percent/100;
}
public String getName()
{
return(this.ame);
}
public double get Salary()
{
return(this.salary);
}
public Employee clone()throws CloneNotSupportedException
{
return ((Employee)super.clone());
}
private String name;
private double salary;
}
public class Employee Test
{
public static void main(String args[])
{
//object creation with default constructor
Employee original=new Employee(“sam”,2000.00);
try
{
Employee copy=original. clone ();
System.out.println (“Before changing”);
System.out.println (“originalobject: Name=”+original.getName () +”sal=”
+original.getSalary ());
System.out.println (“Copy object: Name”+copy.getName()
+”sal=”+copy.getSalary());
copy.raiseSalary(10);
System.out.println (“After Changing the salary of Copy Object”);
System.out.println (“Original Object:Name=”
+original.getName () +”sal=”+original.getSalary());
System.out.println (“copu object:name=”+copy.getName()
+”sal=”+copy.getSalary());
}
catch(CloneNotSupportedException e)
{
system.out.println(e);
}
}
}

Sample input and output


Before Changing
Original Object:Name=samSal=2000.0
Copy Object:NamesamSAl=2000.0
After Changing the Salary of Copy Object
Original Object:Name=samSal=2000.0
Copy Object:Name=samSal=2200.0

Deep Cloning

• Cloning of subclasses is called as Deep Cloning.


• The sub Objects are also copied to new references
• Consider the Date Object in Employee class. Date Object is a
Mutable Object. So needs Deep Cloning.

Example
import java.util.*;
public class Employee implements Cloneable
{
public Employee()
{
salary=500.00;
name=”xxx”;
}
public Employee (String n,double s,int y,int m,int d);
{
salary=s;
name=n;
hireday=newDate(new GregorianCalendar(y,m-1,d).getTimeInMillis());
}
public void raiseSalary(int percent)
{
this.salary=salary+salary*percent/100;
}
public String getName()
{
return(this.name);
}
public double getSalary()
{
return(this.salary);
}
public void setDate()
{
hireday.setTime(new GregorianCalender(2007,7,20).getTimeMillis());
}
public Date getDate()
{
return hireday;
}
public Employee clone() throws CloneNotSupportedException
{
Employee cloned=((Employee)super.clone());
cloned.hireday=(Date)hireday.clone();
return cloned;
}
private String name;
private double salary;
private Date hireday;
}
public class EmployeeTest
{
public static void main(String args[])
{
Employee original=new Employee(“sam”,2000.00,2010,7,23);
try
{
Employee copy=original.clone();
System.out.println(“Before Changing”);
System.out.println(“original object : Name=”+copy.getName()
+”sal=”+original.getSalary()+”HireDay=”+original.getDate());
System.out.println(“Copy Object:Name”+copy.getName()
+”sal=”+copy.getSalary()+”HireDay=”+copy.getDate());
}
catch(CloneNotSupportedException e)
{
System.out.println(e);
}
}
}

Sample input & output


Before changing
Original Object:Name=samSal=2000.0HireDayFri Jul 23 00:00:00:00
GMT+05:30 2010
Copy Object:NamesamSal=2000.0HireDayFri Jul 23 00:00:00
GMT+05:30 2010
After Changing the Salary of Copy Object
Original Object:Name=samSal=2000.0HireDAyFri Jul 23 00
;00:00 GMT+05:30 2010
Copy Object:NamesamSal=2200.0HireDayMon Aug 20 00:00:00
GMT+05:30 2007

Inner classes
An inner class is a class that is defined inside another class. There are
three reasons to have a inner class:
• Inner class methods can access the data from the scope in which
they are defined-including data that would otherwise be private
• inner classes can be hidden from other classes in the same
package
• anonymous inner classes are handy when you want to define
callbacks without writing a lot of code
There are several Inner Classes.They are,
1. Simple inner class-that acess an instance field of its outer
class
2. Local inner classes that can access local variable of the
enclosing scope
3. Anonymouus inner classes and show how they are commonly
used to implement callback
4. Static inner classes can be used for nested helper classes

Simple inner class


• A simple class is a class which is presented inside
another class.
• It is present common inside so that it can be accessed
by all methods of the outer class
• The inner class object can access all fileds of outer
class.
• This is possible because,the inner class object always
gets an implicit reference to the object that created it

inner outer

field1
outer=

field2

• Consider an OuterClass contains a field x and a method


OuterDisplay().
• The InnerClass contains a method DisplayOne().
• The OuterClass method creates an Object for the InnerCLass
and the InnerClass and the InnerClasses accesses the field x of
the OuterClass

Example
public class SimpleInnerClassTest
{
public static void mian(String args[])
{
OuterClass obj=new OuterClass();
obj.outerDisplay();
}
}
class OuterClass
{
private int x=1;
public void outer Display()
{
InnerClass inn=new InnerClass();
inn.DisplayOne();
}
class InnerClass
{
Public void DisplayOne()
{
System.out.println(“This is a simpler Inner Class “);
System.out.println(“the value of variable x is”+x);
}
}
}
Sample input & output
This is simple inner class
The value of variable X is 1

Local Inner Class


• In simple inner class, all the methods of the outer class can
create objects for the inner class.
• Suppose ,if only one method in the outer class wants too create
object for the inner class, then instead of having it common for all
methods, can place it inside a method.
• Local classes are never declared with an access specifies(that is,
public or private).
• Their scope is always restricted to the block in which they are
declared
• Local classes have a great advantage: they are completely
hidden from the outside world-not even other code in the outer
class can access them.
• No method except the method containing the Inner class has any
knowledge of the Inner class.
• Consider an Outerclass contains a field x and a method
outerDisplay().
• The Interclass contains a method DisplayOne() written inside
outerDisplay().The outerclass outerclass() method creates an
object for the InnerCLass and the InnerClass accesses the fields
x of the outerclass.

Example program
public class LocalInnerClassTest
{
public static void main(String args[])
{
OuterClass obj=new OuterClass();
obj.outerDisplay();
}
}
class OuterClass
{
private int x=1;
public void outerDisplay()
{
class InnerClass
{
public void DisplayOne()
{
System.out.println(“this is a local inner class”);
System.out.println(“the vqlue and variable X is”+x);
}
}
InnerClass inn=new InnerClass();
inn.DisplayOne();
}
}

Sample input & output


This is a local Inner class
The value of variable X is 1
Anonymous Inner Class
• When using local inner classes, we can create any number of
Objects for the innerclass.
• If to make only a single object of a class, no need to give the
class name.
• Such a class is called an anonymous inner class

In general,the syntax is

new Super Tpe(construction parameters)


{
inner class methods and data
}

• Here,SuperType can be an interface:then,the inner class


implements that interface.
• Or SuperType can be a class:then,the inner class extends that
class
• An anonymous inner class cannot have constructors because the
name of a aconstructor must be the same as the name of a
class,and the class has no name

Example program
public class ClassAnonTest
{
public static void main(String args[])
{
OuterClassobj=newOuterClass();
obj.displayAnonymous();
}
}
class OuterClass
{
private int x=1;
public void displayAnonymous()
{
Anon inAnon=new Anon)
{
public void displayAnon()
{
System.out.println(“This is Anonmyous Inner Class”);
System.out.println(“The value of x=”+x);
}
}
inAnon.displayAnon();
}
}
interface Anon
{
public void displayAnon();
}

Sample input & output


This is Anonmyous Inner class
The value of x=1

Static Inner Classes


• To use an inner class simply hide one class inside another,but
don’t need the inner class to have a reference to the outer class
object.
• The generation of that reference can be suppressed by declaring
the inner class static
• Consider the task of computing the minimum and maximum
value in an array.
• Of course,you write one method to compute the minimum and
another method to compute the maximum.
• when you call both methods,then the array is traverser twice.it
would be more efficient to traverse the array only
once,computing both the minimum and the maximum
simultaneously
• However,the method must return two numbers.We can acieve
that by defining a class pair that holds two values.
• The minmax functions can then return an object of type pair.The
caller of the function uses the getFirst and getSecond methods to
retrive the answers
Example program

public class StaticInnerClassTest


{
public static void main(String args[])
{
int[]d={5,6,8,1,4,10,12,45};
Outerclass.Pair obj=Outerclass.MinMax(d);
System.out.println(“The minimum value=”+obj.getFirst());
System.out.println(“The Maximum value=”+obj.getSecond());
}
}
class Outerclass
{
public static class Pair
{
public Pair(int f,int s)
{
first=f;
second=s;
}
public int getFirst(){return first;}
public int getSecond(){return second;}
private int first;
private int second;
}
public static Pair MinMax(int[] values)
{
int min=values[0];
int max=values[0];
for (int v:values)
{
if(min>v)min=v;
if(max<v)max=v;
}
return new Pair(min,max);
}
}

Sample input &output


The Minimum value=1;
The maximum value=45

Reflection
• The reflection library gives a very rich and elaborate toolset to
write programs that manipulates Java code dynamically.
• this features is heavily used in JavaBeans,the components
architecture for Java.
• Aprogram that can analyze the capabilities of classes is called
reflective.

The reflection mechanism is extremely powerful.Can use it to


• Analyze the capabilities of classes at runtime;
• Insepct objects at runtime,for example,to write a single to string
method that workes for all classes;
• implement generic array manipulation code;and
• Take advantage of Method objects that works just like function
pointers in language such as c++

Reflection is a powerful and complex mechanism for tool builders,

The Class class


• While program is running, the Java runtime system always
maintains what is called runtime type identification on all objects.
• This information keeps track of the class to which each object
belongs.
• However,you can also access this information by working with a
special Java class.
• The class that holds this information is called,Class

The getClass method in the object class returns an instance of


Class type
Emplyee;

Class cl=e.getClass();

• Just like an Employee object describes the properties of a


particular employee,a Class object describes the properties of a
particular class

Three ways of creating an Object for Class


1. If the name of the object is known,then the Class Object
can be created using gettClass().Then use
getName(),which returns the name of the class.For
example,the statement

Class c=e.getClass().getName();

2. Can obtain a Class object corresponding to a class name


by using the static forName method

String className=”java.util.Date”;
Class cl=Class.forName(className);

3. A third method for obtaining an object of type Class.if T is


any Java type,then T.class is the matching class
object.For example

Class cl1=Date.class;

Using Reflection to Analyze the Capabilities of classes

The most important part of the reflection mechanism is to examine the


structure of a class.The three classes

1.Field
2.Method,and
3.Constructor in the java.lang.reflect package describe the
fields,methods,and constructor of a class, respectively

Field Method Constructor


getName() Returns the Return the Return name
name of the name of the of the
Field Method constructor
getType() Describes _ _
the field type
getParameterTypes() - Report the Report the
types of the types of the
parameter parameters
getReturnType() - Return the _
return type
getModifier() Returns an Returns an Returns an
integer which integer which integer which
describes the describes the describes the
modifiers modifiers modifiers
used such as used such as used,such as
public and public and public and
static static static

Reflection example program

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionExample {

public static void main(String[] args) {


try {
// Creates an object of type Class which contains the information
of
// the class String
Class cl = Class.forName("java.lang.String");

// getDeclaredFields() returns all the constructors of the class.


Constructor cnst[] = cl.getConstructors();

// getFields() returns all the declared fields of the class.


Field fld[] = cl.getDeclaredFields();

// getMethods() returns all the declared methods of the class.


Method mtd[] = cl.getMethods();
System.out.println("Name of the Constructors of the String class")
;

for (int i = 0; i < cnst.length; i++) {


System.out.println(cnst[i].getName());
}

System.out.println("Name of the Declared fields");

for (int i = 0; i < fld.length; i++) {


System.out.println(fld[i].getName());
}

System.out.println("Name of the Methods");

for (int i = 0; i < mtd.length; i++) {


System.out.println(mtd[i].getName());
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Das könnte Ihnen auch gefallen