Vous êtes sur la page 1sur 38

Unit II INHERITANCE

Inheritance is a compile time mechanism in JAVA, that allows you to extends a class called the base class or super class with another class called the derived class or subclass. Simply inheritance means can create new class that are built on existing classes. When inherited from an existing class, can reuse its methods and fields and can add new methods and field to adapt the new class to new situations. In JAVA, inheritance is used for two purposes

Class Inheritance Interface Inheritance INTERFACE INHERITANCE: It creates a new class to implements the methods defined as an part of inheritance for the purpose of subtyping. That is a class that implements an interface conforms to (or) it constrained by the type of the interface. Java supports multiinterface inheritance.

CLASS INHERITANCE: It creates a new class as an extention of another class primarily for the purpose of code reuse. (ie) The derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class. There are two types in it, Single Inheritance Multilevel Inheritance

SINGLE INHERITANCE: When a subclass derived simply from its parent class then this mechanism is known as single inheritance.(there is only a subclass and its parent class) PROGRAM: class A { int a; int b; void getdata(int x,int y) { a=x; b=y; } void display() { System.out.println(a); } } Class B extends A { Public static void main(String args[]) A a1=new A(); A1.getdata(10,6); A.display(); System.out.println(The value of B is+b); } MULTILEVEL INHERITANCE: When a subclass is derived from a derived class this mechanism is known as multilevel inheritance The derived class is called the subclass or child class for its parent class and this parent class works as the child class. Multilevel inheritance can go up to any number of level.

PROGRAM: class A { int m; int n; void getdata(int x,int y) { m=x; n=y; } } Class B extends A { Void display() { System.out.println(m is +a); } } Class C extends B { Void show() { System.out.println(n is +n); } Public static void main(string args[]) { A p=new A() p.getdata(10,5); p.display(); p.show(); } } ADVANTAGES OF INHERITANCE: New classes can be derived by the user from the existing classes without modification.

It saves time and memory. It reduces program coding time. It increases the reliability of the program CLASS HIERARCHY

Inheritance need not stop at deriving one layer of classes. We could have an Executive class that extends Manager, for example

INHERITANCE HIERARCHY: The collection of all classes extending from a common superclass. INHERITANCE CHAIN: The path from a particular class to its ancestors in the inheritance hierarchy.

Employee

Manager

Secretary

Programmer

Executive

POLYMORPHISM Polymorphism is the ability of an object to take on many forms the most common use of polymorphism in oop occurs when a parent class reference is use to refer a child class object. A Simple rule enables to know whether inheritance is the right design for your data. The is-a rule states that every object of the subclass is an object of the superclass. For example, every manager is an employee. Thus, it makes sense for the Manager class to be a subclass of the Employee class. Naturally, the opposite is not true-not every employee is a manager. Another way of formulating the is-a rule is the substitution principle. That principle states that you can use a subclass object whenever the program expects a superclass object. For example, you can assign a subclass object to a superclass variables. Employee e; e=new Employee(..) // Employee object expected e=new Manager(.) // OK, Manager can be used as well In Java programming language, object variables are polymorphic.

PROGRAM: import java.io.*; interface Shape2d { double getArea(); } class shape { void display(string s) {

System.out.println(Name of the shape is+s); } } class circle extends shape implements Shape2d { int radius; circle(int radius) { this.radius=radius; } public double getArea() { return Math.PI*radius*radius; } } class Square extends shape implements Shape2d { int side; Square(int Side) { this.side=side; } public double getArea() { return side*side; } class CircleSquareDemo { public static void main(string args[])throws IOException { Circle c=new Circle(10); c.display(Circle) System.out.println(Area of the circle is:+c.getArea()); Square s=new Square(10); s.display(Square); System.out.println(Area of the square is:+c.getArea()); } }

FINAL KEYWORD FINAL CLASS: Classes that cannot be extended are called final classes. Use the final modifier in the class definition to prevent Inheritance. All methods in a final class are automatically final.

Example: final class Executive Manager { .. } FINAL METHODS: A Specific method in a class can also be final. If you do this, then no subclass can override that method. Example: class Employee { . public final String getName() { return name; } .. }

ABSTRACT CLASSES As you move up the inheritance hierarchy,classes become more general and probably more abstract. Consider, for example, an extension of our Employee class hierarchy. An employee is a person,and so is a student. Let us extend our class hierarchy to include classes person and Student.

person

Employee

Student

Both students and employees have the attribute name in common.So add the name field into a common superclass Person and its corresponding methods. Now lets add another method,getDescription,whose purpose is to return a brief description of the person,such as An employee with a salary of 50,000.00 A student majoring in computer science It is easy to implement this method for the Employee and Student classes.The person class knows only persons name getDescription to return an empty string. If you use the abstract keyword,you do not need to implement the method at all

public abstract String getDescription(); In addition to abstract method,abstract classes can have fields and concrete methods. For example,the person class stores the name of the person and has a concrete method that returns it. PROGRAM: abstract class person { public person(String n) { name=n; } public abstract String getDescription(); public String getName(); { return name; } private String name; } When you extend an abstract class,you have two choices, You can leave some or all of the abstract methods undefined. You can defined all methods. Then the subclass is no longer abstract INTERFACE An interface is a collection of method defining and constant values. An interface is a way of describing what classes should do, without specifying how they should do it. An interface is not a class but a set of requirements for classes that want to conform to the interface. Java doesnot support multiple inheritance so we cannot derive a class from more than one super class.

Most of the applications require multiple inheritance and it can be implemented using interface the methods in the interface contains only the declaration part. This methods have no body. One class can implement any number of interfaces. When we use interface with class it can implement any number of interfaces. USES OF INTERFACES: Capturing similarities between unrelated classes without forcing a class relationship. Declaring method implementations from an interface. Revealing an objects programming interface without revealing its class. (objects such as these are called anonymous objects and can be useful when shipping a package of classes to other developers.) SYNTAX: public area interface { datatype variable value; return method name; } TYPES OF INTERFACE: There are two types of interfaces, they are Extended interface Implementing interface EXTENDED INTERFACE: Deriving new interface from an existing interface is called extended interface. SYNTAX: Interface new classname extends old class name { variable name; method name; } SAMLPE PROGRAM: Interface measure { int a,b,c;

void area(); } Interface advancemeasure extends measure { int d; Void volume(); } IMPLEMENTING INTERFACE: A defined interface can be implemented in any class. So all variables and methods inherits from interface to class. SYNTAX: access class classname implements interface1,interface2,.... { Class body; } TO MAKE A CLASS IMPLEMENT AN INTERFACE, CARRY OUT IN TWO STEPS: Declare that the class indents 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: Class advancemeasure implements measure SAMPLE PROGRAM: import java.io.*; interface IntFace1 { int j=20; int j1(); } interface IntFace2 { double k1(); } interface IntFace3 extends IntFace1,IntFace2 { boolean L1; }

class sample implements IntFace3 { public int j1() { return 100; } public double k1() { return 20.9; } public boolean L1() { return true; } public class IntFace demo2 { public static void main(String args[]) { Sample s=new sample(); System.out.println(s.j); System.out.println(s.j1()); System.out.println(s.k1()); System.out.println(s.L1()); } } PROPERTIES OF INTERFACES: Interfaces are not classes. Cannot use the new operator to instantiate an interface: X=new comparable(..);//ERROR However, can still declare interface variables. Comparable x;//ERROR An interface variable must refer to an object of a class that implements the interface: X=new employee(..);//OK employee must implements comparable Use instance of tocheck whether an object implements an interface: if(an object instance of comparable){} Just as you can build hierarchies of classes, you can extend interfaces. For example, suppose you had an interface called moveable.

public interface moveable { Void move(double x, double y); } Then you could imagine an interface called powered that extends it: Public interface powered extends moveable { double milespergallon(); } Cannot put instance fields or static methods in an interface. Can supply constants in them. For example, public interface powered extends moveable { double milespergallon(); double SPEED_LIMIT=95;//a public static final cons. } Method in an interface are automatically public, fields are always public static final. Each class can have only one superclass, classes can implements multiple interfaces. This gives you the maximum amount of flexibility in defining a classs behaviour class employee implements cloneable, comparable. INTERFACES AND ABSTRACT CLASSES: There are situations in which you will want to define a superclass that declares the structures of a given abstraction without providing a complete implementation of every method. It defines the generalized form that will shared by all of its subclasses, leaving it to each subclass to fill in the details. abstract type name(parameter_lists); SYNTAX: abstract class comparable { Public abstract int compare To(object other); } The employee class would then simply extends this abstract class and supply the compare To method:

Class employee extends comparable//why not? { Public int compare To(object other){...} } There is, unfortunately, a major problem with using an abstract base class to express a generic property. A class can only extend a single class. Suppose that the employee class class extends a different class, say, person. Then it cant extend a second class. Class employee extents person,comparable//ERROR Therefore each class can implements many of the interfaces. PROXIES: Proxies are used to create at runtime new classes that implements a given set of interfaces proxies are only necessary when not yet know at compile time which interfaces needed to implement. This is a common situation for application programmers, but for certain system programming applications, the flexibility that proxies offer can be veryimportant. The proxy class can create brand-new classes at runtime. Such a proxy class implements the interfaces specified. The proxy class has the following methods: o All methods required by the specified interface;and o All methods defined in the object class (toString, equals and so on) o Cannot define new code for these methods at runtime. Instead, must supply an invocation handler. An invocation handler is an object of any class that implements the InvocationHandler interface. That interface has a single method: Object invoke(object proxy,Method method, object[] args) Whenever a method is called on the proxy object, the invoke method of the invocation handler gets called, with the Method object and parameters of the original call.

o An array of class objects, one for each interface to be implemented. o An invocation handler. : o A class loader. As a part of the Java security model, different class loaders for system classes, classes that are downloaded from the Internet, and so on, can be used. For now, we specify null to use the default class loader. o An array of class objects, one for each interface to be implemented. o An invocation handler. Proxies can be used for many purposes, such as o Routing method calls to remote servers; o Tracing method calls for debugging purposes. o A proxy interface is such an interface that is implemented by a proxy class. o A proxy instance is an instance of a proxy class. o Associating user interface events with actions in arunning program.

PROPERTIES OF PROXY CLASS: Proxy class are public, final, and not abstract. A proxy class extends java.lang.reflect.proxy. Each proxy class has one public constructor that takes one argument. It a proxy class implements a non-public interface.

BASEINTERFACE

METHOD1() METHOD2()

CLIENT

PROXY METAL OBJECT INVOCATION HANDLER CONCRETE COMPONENTS

METHOD1() METHOD2()

METHOD1() METHOD2()

METHOD METHOD

PROXIES

Sample program: import java.lang.reflect.*; public static void main(String args[]) { String value= new String(HELLO); //gives all the interfaces implemented by the String class class[] interfaces=value.getclass().getInterfaces(); for(class k:interfaces) { System.out.println(k.getName()); } InvocationHandler h=new proxytrace(value); Object pro=proxy.newProxyInstance (value.getclass().getclassLoader(),interfaces,h); // pro object calls the invoke method System.out.println(pro.equals(HELLO)); }

} Another program: import java.lang.reflex.*; import java.util.*; public class proxytrace implements InvocationHandler { public proxytrace(Object o) { //stores the client object information target=0; } public object invoke(object proxy,methodm,object[]args) //throws throwable { System.out.println(trace); return m.invoke(tatget,args); } private object target; } PROGRAM: class Box { double height; double depth; double width; } class Box demo { Public static void main(String args[]) { Box B1=new box(); Box B2=new box(); double vol1; double vol2; B1.height=30;

B1.depth=20; B1.width=10; B2.height=40; B2.depth=50; B2.width=15; vol1=(B1.height*B1.depth*B1.width); System.out.println(volume is +vol1); vol2=(B2.height*B2.depth*B2.width); System.out.println(volume is +vol2); } }

PROGRAM FOR METHODS: class Area { Public static void main(String args[]) { int l=10; int b=20; int Area=calculate Area(); System.out.println(The Area); } public static int calculate Area() { int method Area=l*b; return method area; } } STATIC METHODS: class demo { static int age,height; static void display(int age,int height) {

System.out.println(Age= +age); System.out.println(Height= +height); } public static void main(String args[]) { display(5,100); } }

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);//OKoriginal 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 name salary hireDay string

Original=

Copy=

Employee name salary hireDay date

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 dont 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

getName() getType() getParameterTypes() getReturnType() getModifier()

Field Returns the name of the Field Describes the field type -

Method Return the name of the Method _

Constructor Return name of the constructor _ Report the types of the parameters _ Returns an integer which describes the modifiers used,such as public and static

Report the types of the parameter Return the return type Returns an Returns an integer which integer which describes the describes the modifiers used modifiers used such as public such as public and static and 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(); } } }

Vous aimerez peut-être aussi