Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

40
UNIT II OBJECT-ORIENTED PROGRAMMING – INHERITANCE Inheritance Inheritance is a process of making a new class that derives from an existing class. The existing class is called the superclass, base class, or parent class. The new class is called the subclass, derived class, or child class. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and add its own, unique elements. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class. To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. The general form of a class declaration that inherits a superclass is shown here: class subclass-name extends superclass-name { // body of class }

description

OBJECT-ORIENTED PROGRAMMING – INHERITANCE core java notes

Transcript of Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

Page 1: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

UNIT II OBJECT-ORIENTED PROGRAMMING – INHERITANCE

Inheritance

Inheritance is a process of making a new class that derives from an existing class. The existing class is called the superclass, base class, or parent class. The new class is called the subclass, derived class, or child class.

Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and add its own, unique elements.

Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. The general form of a class declaration that inherits a superclass is shown here:

class subclass-name extends superclass-name

{

// body of class

}

You can only specify one superclass for any subclass that you create. Java does not support the inheritance of multiple superclasses into a single subclass.

Protected features in Java are visible to all subclasses as well as all other classes in the same package.

Member Access and Inheritance

A class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including subclasses.

Super keyword

Page 2: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

Super is a special keyword that directs the compiler to invoke the superclass method. super has two general forms.

to invoke a superclass constructor.

to invoke a superclass members(variables &methods). invoke a superclass constructor .

Invoke superclass constructor:

A subclass can call a constructor method defined by its superclass by use of the following form of super:

super(parameter-list);

Here, parameter-list specifies any parameters needed by the constructor in the superclass.

super( ) must always be the first statement executed inside a subclass constructor.

The compiler implicitly calls the base class’s no-parameter constructor or default constructor.

If the superclass has parameterized constructor and the subclass constructor does not call superclass constructor explicitly, then the Java compiler reports an error.

Invoke superclass members:

Super always refers to the superclass of the subclass in which it is used. This usage has the following general form:

super.member;

Here, member can be either a method or an instance variable. This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass.

If a parent class contains a finalize() method, it must be called explicitly by the derived class’s finalize() method.

Page 3: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

super.finalize();

When Constructors are Called

Constructors are called in order of derivation, from superclass to subclass. Because a superclass has no knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it must be executed first.

CLASS HIERARCHY

The collection of all classes extending from a common superclass is called an inheritance hierarchy; the path from a particular class to its ancestors in the inheritance hierarchy is its inheritance chain.

Simple class hierarchies consist of only a superclass and a subclass. But you can build hierarchies that contain as many layers of inheritance as you like.

For example, create three classes called A, B, and C, C can be a subclass of B, which is a subclass of A. When this type of situation occurs, each subclass inherits all of the traits found in all of its superclasses. In this case, C inherits all aspects of B and A.

POLYMORPHISM

Polymorphism means the ability of methods to behave differently based on the kinds of input.

Types of polymorphism

Method Overloading

Method overriding

Overloaded methods

Overloaded methods are methods with the same name but different method signature (either a different number of parameters or different types in the parameter list).

public class Test{

Page 4: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

public static void main(String arg[]){

A a=new A();

a.display();

B b=new B();

b.display("Hello");

}

}

class A{

void display(){

System.out.println("Hai");

}

}

class B extends A{

void display(String s){

System.out.println(s);

}

}

Output

Hai

Hello

Overridden methods

The process of a subclass redefining a method contained in the superclass (with the same parameter types) is called overriding the method.

Page 5: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

Overridden methods allow Java to support run time polymorphism. Whenever a method is called for a subclass object, the compiler calls the overriding version instead of the superclass version. The version of the method defined by the superclass will be hidden.

Call to an overridden method is resolved at run time, rather than compile time. Superclass reference variable can refer to a subclass object. Java uses this fact to resolve calls to overridden methods at run time. When an overridden method is called through a superclass reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. This determination is made at run time.

class Dispatch {

public static void main(String args[]) {

A a = new A(); // object of type A

B b = new B(); // object of type B

C c = new C(); // object of type C

A r; // obtain a reference of type A

r = a; // r refers to an A object

r.callme(); // calls A's version of callme

r = b; // r refers to a B object

r.callme(); // calls B's version of callme

r = c; // r refers to a C object

r.callme(); // calls C's version of callme

}

}

When you override a method, the subclass method must be at least as visible as the superclass method.

Page 6: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

In particular, if the superclass method is public, then the subclass method must also be declared as public. It is a common error to accidentally omit the public specifier for the subclass method. Then the compiler complains that you try to supply a weaker access privilege.

public class Test1{

public static void main(String arg[]){

A a=new A();

a.display();

B b=new B();

b.display();

}

}

class A{

protected void display(){

System.out.println("Hai");

}

}

class B extends A{

public void display(){

System.out.println("Hello");

}

}

Output

Hai

Page 7: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

Hello

Methods labeled final, private, or static are not subject to dynamic lookup because they may not be overridden. private methods are simply not inherited because they would never be callable anyway. static methods apply to a particular class’s static data and thus make no sense in a derivation. final methods are those designated as not-overridable for reasons of complexity or safety.

public class Test1{

public static void main(String arg[]){

A a1=new A();

a1.display();

A a2=new B();

a2.display();

}

}

class A{

void display(){

System.out.println("Hai");

}

}

class B extends A{

void display(){

System.out.println("Hello");

}

}

Page 8: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

Output

Hai

Hello

DYNAMIC BINDING

Selecting the appropriate method at runtime is called dynamic binding. Dynamic Binding refers to the case where compiler is not able to resolve the call and the binding is done at runtime only.

All the instance methods in Java follow dynamic binding.

Dynamic binding has a very important property:

It makes programs extensible without recompiling the existing code.

Suppose a new class is added, and there is the possibility that the variable refers to an object of that class. The code contains the method invoking statement of that class need not be recompiled. The method is called automatically if the object happens to refer to the class.

Dynamic Binding or Late Binding

It is important to understand what happens when a method call is applied to an object. Here are the details:

1. The compiler looks at the declared type of the object and the method name. The compiler knows all possible candidates for the method to be called.

2. Next, the compiler determines the types of the parameters that are supplied in the method call. If among all the methods called fun there is a unique method whose parameter types are a best match for the supplied parameters, then that method is chosen to be called. This process is called overloading resolution.

3. If the method is private, static, final, or a constructor, then the compiler knows exactly which method to call.

4. When the program runs and uses dynamic binding to call a method, then the virtual machine must call the version of the method that is appropriate for the

Page 9: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

actual type of the object. The virtual machine precomputes a method table for each class that lists all method signatures and the actual methods to be called. When a method is actually called, the virtual machine simply makes a table lookup. This is used to reduce the time consumed by searching process.

STATIC BINDING OR EARLY BINDING

If the compiler can resolve the binding at the compile time only then such a binding is called Static Binding or Early Binding. Resolve the call and binding at compile time.

If the method is private, static, final, or a constructor, then the compiler knows exactly which method to call. This is called static binding.

All the member variables in Java follow static binding.

All the static method calls are resolved at compile time itself.

All private methods are resolved at compile time itself.

FINAL KEYWORD

The keyword final has three uses.

Used to create the equivalent of a named constant.

Used to Prevent Overriding

Used to Prevent Inheritance

Named constant

A variable can be declared as final. Doing so prevents its contents from being modified. This means that you must initialize a final variable when it is declared. For example:

final int constant = 1;

Variables declared as final do not occupy memory on a per-instance basis. Thus, a final variable is essentially a constant. The keyword final can also be applied to methods, but its meaning is substantially different than when it is applied to

Page 10: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

variables. Attempts to change it will generate either a compile-time error or an exception.

Using final to Prevent Overriding

Methods declared as final cannot be overridden.The syntax is simple, just put the keyword final after the access specifier and before the return type like this:

class A

{

final void meth() {

System.out.println("This is a final method.");

}

}

class B extends A

{

void meth() { // ERROR! Can't override.

System.out.println("Illegal!");

}

}

Normally, Java resolves calls to methods dynamically, at run time. This is called late binding. However, since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early binding.

Using final to Prevent Inheritance

Declaring a class as final implicitly declares all of its methods as final. So it prevents a class from being inherited. To do this, precede the class declaration with final.

Page 11: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

It is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.

Here is an example of a final class:

final class A

{

// ...

}

// The following class is illegal.

class B extends A

{ // ERROR! Can't subclass A

// ...

}

ABSTRACT CLASSES

An abstract class is a type of class that is not allowed to be instantiated. The only reason it exists is to be extended. Abstract classes contain methods and variables common to all the subclasses, but the abstract class itself is of a type that will not be used directly. Even a single abstract method requires that a class be marked abstract.

To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration.

abstract class classname

{

public abstract type methodname();

// no implementation required

Page 12: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

……..

}

There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined.

Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract.

Here is a simple example of a class with an abstract method, followed by a class which implements that method:

// A Simple demonstration of abstract.

abstract class A

{

abstract void callme();// concrete methods are still allowed in abstract classes

void callmetoo() {

System.out.println("This is a concrete method.");

}

}

class B extends A

{

void callme() {

System.out.println("B's implementation of callme.");

}

}

Page 13: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

class AbstractDemo

{

public static void main(String args[]) {

B b = new B();

b.callme();

b.callmetoo();

}

}

That is, sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass.

Thus, a subclass must override them—it cannot simply use the version defined in the superclass.

Abstract methods

An abstract method is a method declaration that contains no functional code. The reason for using an abstract method is to ensure that subclasses of this class will include an implementation of this method. Any concrete class (that is, a class that is not abstract, and therefore capable of being instantiated) must implement all abstract methods it has inherited.

Methods declared with the keyword abstract define a skeleton for a method but do not implement it. This requires a derived class to provide the code for this class.

A class with one or more abstract methods must itself be declared abstract and cannot be instantiated. It can only be used for derivation.

Page 14: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

To declare an abstract method, use this general form:

abstract type name(parameter-list);

But while an abstract class can define both abstract and nonabstract methods, an interface can have only abstract methods. Interface as being similar to an abstract class with no instance fields.

Interfaces

An interface is a collection of method definitions (without implementations) and constant values.

Defining an Interface

This is the general form of an interface:

An interface must be declared with the keyword interface.

access interface name {

return-type method-name(parameter-list);

type final-varname = value;

}

It is also possible to declare that an interface is protected so that it can only be

implemented by classes in a particular package. However this is very unusual.

Rules for interface constants. They must always be

public

static

final

Once the value has been assigned, the value can never be modified. The assignment happens in the interface itself (where the constant is declared), so the implementing class can access it and use it, but as a read-only value.

Page 15: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

To make a class implement an interface, have to carry out two steps:

Declare that your class intends to implement the given interface.

Supply definitions for all methods in the interface.

To declare that a class implements an interface, use the implements keyword:

access class classname implements interfacename

{

//definitions for all methods in the interface

}

Implementation classes must adhere to the same rules for method implementation as a class extending an abstract class. In order to be a legal implementation class, a nonabstract implementation class must do the following:

When you implement an interface method, method must be declared as public. (The access level can be more accessible than that of the overridden method.)

Type signature of the implementing method must match exactly the type signature specified in the interface definition. (The argument list and return type must exactly match that of the overridden method.)

A class can implement one or more interfaces.

Partial Implementations: If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract.

Inner Classes

An inner class is a class that is defined inside another class.

Inner classes let you make one class a member of another class. Just as classes have member variables and methods, a class can also have member classes.

Page 16: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

Regular Inner Class

You define an inner class within the curly braces of the outer class, as follows:

class MyOuter {

class MyInner { }

}

And if you compile it, %javac MyOuter.java , you’ll end up with two class files:

MyOuter.class

MyOuter$MyInner.class

The inner class is still, in the end, a separate class, so a class file is generated. But the inner class file isn’t accessible to you in the usual way. The only way you can access the inner class is through a live instance of the outer class.

Instantiating an Inner Class

To instantiate an instance of an inner class, you must have an instance of the outer class. An inner class instance can never stand alone without a direct relationship with a specific instance of the outer class.

Instantiating an Inner Class from Within Code in the Outer Class

From inside the outer class instance code, use the inner class name in the normal way:

class MyOuter {

private int x = 7;

MyInner mi = new MyInner();

class MyInner {

public void seeOuter() {

System.out.println("Outer x is " + x);

Page 17: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

}

}

public static void main(String arg[]){

MyOuter mo=new MyOuter();

mo.mi.seeOuter();

}

}

Output:

Outer x is 7

Method-Local Inner Classes

A method-local inner class is defined within a method of the enclosing class. class MyOuter {

void inner()

{

final int c=9;

class MyInner {

int x=5;

public void display() {

System.out.println("Inner x is " + x);

System.out.println("Inner c is " + c);

}

}

MyInner mi = new MyInner();

Page 18: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

mi.display();

}

public static void main(String arg[]){

MyOuter mo = new MyOuter();

mo.inner();

}

}

Output: x is 5

c is 9

Anonymous Inner Classes

Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface.

An anonymous inner class is always created as part of a statement, so the syntax will end the class definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a semicolon to end the statement: });

An anonymous inner class can extend one subclass, or implement one interface. It cannot both extend a class and implement an interface, nor can it implement more than one interface.

public class Test{

public static void main(String arg[]){

B b=new B();

b.ob.display();

}

}

Page 19: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

class A{

void display(){

System.out.println("Hai");

}

}

class B {

A ob=new A(){

void display(){

System.out.println("Hello");

}

};

}

Output: Hello

And if you compile it, %javac Test.java , you’ll end up with two class files:

A.class

B.class

B$1.class

Test.class

Static Nested Classes

Static nested classes are inner classes marked with the static modifier.

Technically, a static nested class is not an inner class, but instead is considered a top-level nested class.

Page 20: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

Because the nested class is static, it does not share any special relationship with an instance of the outer class. In fact, you don’t need an instance of the outer class to instantiate a static nested class.

Instantiating a static nested class requires using both the outer and nested class names as follows:

BigOuter.Nested n = new BigOuter.Nested();

A static nested class cannot access nonstatic members of the outer class, since it does not have an implicit reference to any outer instance (in other words, the nested class instance does not get an outer this reference).

public class Test{

public static void main(String arg[]){

A.B b=new A.B();

b.display();

}}

class A {

static class B {

int m=5;

void display(){

System.out.println("m="+m);

}

}

Page 21: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

}

Output: m=5

The Object Class - The Cosmic Superclass

The Object class sits at the top of the class hierarchy tree in the Java development environment. The Object class is the ultimate ancestor

Every class in Java extends Object class.

The Object class defines the basic state and behavior that all objects must have, such as the ability to compare with 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.

Object defines the following methods, which means that they are available in every object.

Reflection

Reflection is the ability of the software to analyze itself at runtime.

Reflection is provided by the java.lang.reflect package and elements in class.

This mechanism is helpful to tool builders, not application programmers.

The reflection mechanism is extremely used to

Analyze the capabilities of classes at run time

Inspect objects at run time

Implement generic array manipulation code

Analyze the capabilities of classes at run time - Examine the structure of class.

Page 22: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

Methods (Field, Method & Constructor):

String getName() – return the name of the item.

int getModifiers()- return an integer, that describes the modifier.

Field

Provide information about fields.

The getFields method returns an array containing Field objects for the public fields.

The getDeclaredField method returns an array of Field objects for all fields. The methods return an array of length 0 if there are no such fields.

import java.lang.reflect.*;

class Test{

public int var1;

private int var2;

protected int var3;

int var4;

}

Page 23: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

public class FieldDemo{

public static void main(String args[])throws Exception{

Class c=Class.forName("Test");

Field f[]=c.getFields();

Field fdec[]=c.getDeclaredFields();

System.out.println("public Fields:");

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

System.out.println(f[i]);

System.out.println("All Fields:");

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

System.out.println(fdec[i]);

}

}

Output:

public Fields:

public int Test.var1

All Fields:

public int Test.var1

private int Test.var2

protected int Test.var3

int Test.var4

Method

Provides information about method

Page 24: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

The getMethods() method return an array containing Method objects that give you all the public methods.

The getDeclaredMethods () return all methods of the class or interface. This includes those inherited from classes or interfaces above it in the inheritance chain.

import java.lang.reflect.*;

class Test{

public void method1()

{}

protected void method2()

{}

private void method3()

{}

void method4()

{}

}

public class MethodDemo{

public static void main(String args[])throws Exception{

Class c=Class.forName("Test");

Method m[]=c.getMethods();

Method mdec[]=c.getDeclaredMethods();

System.out.println("public Methods of class Test & its Super class:");

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

System.out.println(m[i].getName());

Page 25: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

System.out.println("All Methods:");

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

System.out.println(mdec[i].getName());

}

}

Output:

public Methods of class Test & its Super

class:

method1

hashCode

getClass

wait

equals

notify

notifyAll

toString

All Methods:

method1

method2

method3

method4

Constructor

Provide information about constructors

Page 26: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

getConstructors () method return an array containing Constructor objects that give you all the public constructors

getDeclaredConstructors () method return all constructors of the class represented by the Class object.

Using Reflection to Analyze Objects at Run Time

Look at the contents of the data fields. It is easy to look at the contents of a specific field of an object whose name and type are known when you write a program. But reflection lets you look at fields of objects that were not known at compile time.

f.set(obj, value) sets the field represented by f of the object obj to the new value.

f.get(obj) returns an object whose value is the current value of the field of obj.

import java.lang.reflect.*;

class A{

public int var1,var2;

A(int i, int j){

var1=i;

var2=j;

}

}

public class ConstructorDemo {

public static void main(String args[]) throws Exception{

A obj=new A(10,20);

System.out.println("Before \n var1= "+obj.var1);

Field f1 = obj.getClass().getField("var1");

Page 27: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

int v1 = f1.getInt(obj) + 1;

f1.setInt(obj, v1);

System.out.println("After \n var1= "+v1);

System.out.println("Before \n var2= "+obj.var2);

Field f2 = obj.getClass().getField("var2");

f2.set(obj,21);

System.out.println("After \n var2= "+f2.get(obj));

}

}

Output:

Before var1= 10

After

var1= 11

Before var2= 20

After

var2= 21

Using Reflection to implement generic array manipulation code

The Array class in the java.lang.reflect package allows you to create arrays dynamically. First the given array can be converted to an Object[] array. newInstance() method of Array class, constructs a new array.

Object newarray= Array.newInstance(ComponentType, newlength)

newInstance() method needs two parameters

Component Type of new array

Page 28: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

To get component type

1. Get the class object using getClass() method.

2. Confirm that it is really an array using isArray().

3. Use getComponentType method of class Class, to find the right type for the array.

Length of new array

Length is obtained by getLength() method. It returns the length of any array(method is static method, Array.getLengh(array name)).

import java.lang.reflect.*;

public class TestArrayRef {

static Object arrayGrow(Object a){

Class cl = a.getClass();

if (!cl.isArray()) return null;

Class componentType = cl.getComponentType();

int length = Array.getLength(a);

int newLength = length + 10;

Object newArray = Array.newInstance(componentType,newLength);

System.arraycopy(a, 0, newArray, 0, length);

return newArray;

}

public static void main(String args[]) throws Exception{

int arr[]=new int[10];

System.out.println(arr.length);

Page 29: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

arr = (int[])arrayGrow(arr);

System.out.println(arr.length);

}

}

Output:

10

20

Object cloning

A clone of an object is a new object that has the same state as the original but a different identity. You can modify the clone without affecting the original.When you make a copy of a variable, the original and the copy are references to the same object. This means a change to either variable also affects the other. If you want to make a clone of any class then the class must

implement the Cloneable interface, and

Redefine the clone method with the public access modifier.

import java.util.*;

class Test implements Cloneable{

int a=10;

public void display(){

System.out.println("a="+a);

}

public Object clone(){

try{

Test cloned = (Test)super.clone();

Page 30: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

return cloned;

}

catch(CloneNotSupportedException e){

return null;

}

}

}

public class CloneDemo{

public static void main(String arg[]){

Test original=new Test();

original.a=20;

Test copy=(Test)original.clone();

copy.a=80;

original.display();

copy.display();

}

}

Output:

a=20

a=80

Proxy

Page 31: Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE

Proxy used to create new classes at runtime that implement a given set of interfaces. The proxy class can create brand-new classes at runtime. The proxy class can create brand-new classes at runtime. Such a proxy class implements

the interfaces that you specify. In particular, the proxy class has the following methods:

• All methods required by the specified interfaces;

• All methods defined in the Object class (toString, equals, and so on).

To create a proxy object, you use the newProxyInstance method of the Proxy class. The method has three parameters:

1. A class loader. As part of the Java security model, it is possible to use different

class loaders for system classes, classes that are downloaded from the Internet,

and so on.

2. An array of Class objects, one for each interface to be implemented.

3. An invocation handler.

Proxies can be used for many purposes, such as:

• Routing method calls to remote servers;

• Associating user interface events with actions in a running program;

• Tracing method calls for debugging purposes.