You are on page 1of 38


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();; } } ADVANTAGES OF INHERITANCE: • New classes can be derived by the user from the existing classes without modification.

It reduces program coding time. INHERITANCE CHAIN: The path from a particular class to its ancestors in the inheritance hierarchy. Employee Manager Secretary Programmer Executive .• • • It saves time and memory. 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.

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. object variables are polymorphic. For example.*. • That principle states that you can use a subclass object whenever the program expects a superclass object. • The “is-a” rule states that every object of the subclass is an object of the • For example. Naturally. } class shape { void display(string s) { . it makes sense for the Manager class to be a subclass of the Employee class. Manager can be used as well • In Java programming language.) // OK. interface Shape2d { double getArea(). Employee e. the opposite is not true-not every employee is a manager. every manager is an employee. • Another way of formulating the “is-a” rule is the substitution principle. you can assign a subclass object to a superclass variables. PROGRAM: import java.. • A Simple rule enables to know whether inheritance is the right design for your data. • Thus.) // Employee object expected e=new Manager(……. e=new Employee(….

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

FINAL KEYWORD FINAL CLASS: Classes that cannot be extended are called final classes. then no subclass can override that method. If you do this. • Example: final class Executive Manager { ….. • All methods in a final class are automatically final. } FINAL METHODS: • • A Specific method in a class can also be final. Use the final modifier in the class definition to prevent Inheritance. } …. } . Example: class Employee { ……. public final String getName() { return name..

The person class knows only persons name • getDescription to return an empty string.such as • An employee with a salary of 50.ABSTRACT CLASSES • As you move up the inheritance hierarchy.00 • A student majoring in computer science • It is easy to implement this method for the Employee and Student classes. for example.getDescription.So add the name field into a common superclass Person and its corresponding methods. • 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.whose purpose is to return a brief description of the person. • If you use the abstract keyword.classes become more general and probably more do not need to implement the method at all . • Consider. An employee is a person.000. • Now let’s add another method.and so is a student. an extension of our Employee class hierarchy.

• You can leave some or all of the abstract methods undefined. public String getName(). { return name. • For example. PROGRAM: abstract class person { public person(String n) { name=n.abstract classes can have fields and concrete have two choices. 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. } When you extend an abstract class. • . • In addition to abstract method. } private String name.the person class stores the name of the person and has a concrete method that returns it. 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. • Java doesnot support multiple inheritance so we cannot derive a class from more than one super class.public abstract String getDescription(). } public abstract String getDescription(). • You can defined all methods.

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

USE THE IMPLEMENTS KEYWORD: Class advancemeasure implements measure SAMPLE PROGRAM: import java. So all variables and methods inherits from interface to class. SYNTAX: access class classname implements interface1. { Class body.. int j1(). } interface IntFace2 { double k1().*. } Interface advancemeasure extends measure { int d.void area(). …………… } TO MAKE A CLASS IMPLEMENT AN INTERFACE. Void volume(). TO DECLARE THAT A CLASS IMPLEMENTS AN INTERFACE. } IMPLEMENTING INTERFACE: A defined interface can be implemented in any } .IntFace2 { boolean L1. • Supply definitions for all methods in the interface. } interface IntFace3 extends IntFace1. interface IntFace1 { int j=20...interface2. CARRY OUT IN TWO STEPS: • Declare that the class indents to implement the given interface..

System.out. System. System.j1()).. you can extend interfaces.println(s. System. .println(s.//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.out. Comparable x. } public class IntFace demo2 { public static void main(String args[]) { Sample s=new sample(). For example. } } PROPERTIES OF INTERFACES: • Interfaces are not classes.out.L1()).j).k1())..out. Cannot use the new operator to instantiate an interface: X=new comparable(…. } public double k1() { return 20.//ERROR However. } public boolean L1() { return true.//ERROR • An interface variable must refer to an object of a class that implements the interface: X=new employee(…. suppose you had an interface called moveable.println(s.).class sample implements IntFace3 { public int j1() { return 100.9.).println(s. can still declare interface variables.

This gives you the maximum amount of flexibility in defining a class’s behaviour class employee implements cloneable. • It defines the generalized form that will shared by all of its subclasses. double y). leaving it to each subclass to fill in the details.//a public static final cons. 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. For example. • Each class can have only one superclass. } • Cannot put instance fields or static methods in an interface. } Then you could imagine an interface called powered that extends it: Public interface powered extends moveable { double milespergallon(). abstract type name(parameter_lists). • Can supply constants in them. fields are always public static final. classes can implements multiple interfaces. SYNTAX: abstract class comparable { Public abstract int compare To(object other). double SPEED_LIMIT=95. public interface powered extends moveable { double milespergallon().public interface moveable { Void move(double x. } • Method in an interface are automatically public. } The employee class would then simply extends this abstract class and supply the compare To method: .

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

o Tracing method calls for debugging purposes. o An array of class objects. can be used. • A proxy class extends java. PROPERTIES OF PROXY CLASS: • Proxy class are public. . and so on.reflect. As a part of the Java security model. o Associating user interface events with actions in arunning program. one for each interface to be implemented. • It a proxy class implements a non-public interface. we specify null to use the default class loader. o An invocation handler. and not abstract.o An array of class objects. 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 A class loader. different class loaders for system classes.proxy. final. classes that are downloaded from the Internet. • Each proxy class has one public constructor that takes one argument. such as o Routing method calls to remote servers. o An invocation handler. For now. Proxies can be used for many purposes. one for each interface to be implemented.lang.

Object pro=proxy.println(pro.reflect. // pro object calls the invoke method System. //gives all the interfaces implemented by the String class class[] interfaces=value.*.newProxyInstance (value. for(class k:interfaces) { System.lang. public static void main(String args[]) { String value= new String(“HELLO”).out.BASEINTERFACE METHOD1() METHOD2() CLIENT PROXY METAL OBJECT INVOCATION HANDLER CONCRETE COMPONENTS METHOD1() METHOD2() METHOD1() METHOD2() METHOD METHOD PROXIES Sample program: import java.getInterfaces().getclassLoader().getclass().interfaces.out.getclass().h). } .println(k.equals(“HELLO”)).getName()). } InvocationHandler h=new proxytrace(value).

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

int b=20. System. int Area=calculate Area().depth=20.B1.out. } } STATIC METHODS: class demo { static int age.height. static void display(int age. System. return method area. B2.out.width=10.width=15.width).depth* height) { .out.println(“volume is” +vol1). B2.println(“The Area”).println(“volume is” +vol2). System.width). B1. } } PROGRAM FOR METHODS: class Area { Public static void main(String args[]) { int l=10. vol1=(B1.depth=50. B2.height=40.height*B1.height*B2. vol2=(B2. } public static int calculate Area() { int method Area=l*b.depth*B1.

// SuperClass version is called superClass2.System. ..the super class version or the sub class version.println(“Height=” +height). } public static void main(String args[]) { display(5. • Now a 'SuperClass' reference can be assigned to an object of the type 'SubClass' as well. // SubClass version is called . System.. Hence. Suppose we have a class named 'SuperClass' and another class named 'SubClass' extends it.out. 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. superClass1...out.someMethod(). } } 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.someMethod().. we see that even though both the object references superClass1 andsuperClass2 are of type 'SuperClass' only. SuperClass superClass2 = new SubClass(). Here. • Let's try to understand this.. 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 . but at run time they refer to the objects of types 'SuperClass' and 'SubClass' respectively. . SuperClass superClass1 = new SuperClass().println(“Age=” +age).100).. .

Thus. • The Object class defines the basic state and behavior that all objects must have. for equality: Integer one = new Integer(1). This code will display objects are equal even though one and anotherOne reference two different.println("objects are equal"). • if (one. to wait on a condition variable. The Object Class The Object class sits at the top of the class hierarchy tree in the Java development environment. The getClass Method . such as the ability to compare oneself to another object. They are considered equal because they contain the same integer value. • The equals Method Use the equals to compare two objects for equality. 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. to notify other objects that a condition variable has changed. Your equals method should compare the contents of the objects to see if they are functionally equal and return true if they are. • Consider this code that tests two Integers. • Note that equality does not mean that the objects are the same object. one and anotherOne.out. and to return the object's class. to convert to a string. This method returns true if the objects are equal. distinct objects. false otherwise. • Your classes should override this method to provide an appropriate equality test. • Every class in the Java system is a descendent (direct or indirect) of the Object class. anotherOne = new Integer(1).equals(anotherOne)) System.

getClass().getClass(). } The toString Method • Object's toString method returns a String representation of the object. • This method returns a Class object.getName()).out. • For example. its superclass.main] • The toString method is very useful for debugging and it would behoove you to override this method in all your classes.5. .The getClass method is a final method (cannot be overridden) that returns a runtime representation of the class of this object. • The String representation for an object is entirely dependent on the object. you could display a String representation of the current Thread like this: System. the previous of code above display the following: • Thread[main. } 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.currentThread().println(Thread.out.println("The Object's class is " + obj. For example. 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. such as its name.newInstance(). • The String representation of a Thread object contains various attributes about the thread. • You can query the Class object for a variety of information about the class. and the names of the interfaces that it implements. You can use toString to display an object.toString()). such as its name and priority. • The following method gets and displays the class name of an object: void PrintClassName(Object obj) { System. • The String representation of an Integer object is the integer value displayed as text.

raise Salary(10). 50000). the original and the copy objects have references to the same object. Copy.Object cloning • When a copy of a variable is made. Copy.//OK—original unchanged .//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.raiseSalary(10). Employee copy=original. • This means a change to either variable also affects the other Employee original=new Employee (“John Public”.clone().

they are 1. • If the subobject that is shared between the original and the shallow clone is immunable. the default cloe method can be patched up by calling clone on the mutable subobjects(Deep clone) • To do cloning. • This certainly happens if the subobjects belong to an immunable class. Only the Employee class can clone Employee objects. then field by field copying will make the original and copy objects to refer to the same sub-objects. otherwise the subobject may simply remain constant throughout .• The clone method is protected method of object.Implemennt the cloneable interface.and 2. • If each and every field is numbered or basic types their is no problem. • This happens because the object class has no information about the fields of the class which calls the clone method. The default clone method (shallow clone) is enough. a class must 1. need to decide to decide weather 1. then the sharing is safe. there are two types of cloning. Deep cloning • For every class. Shallow cloning-(default cloning method) 2.Redefine the clone method with the public access modifier Cloning Original= employee Copy= employee Shallow Cloning • Shallow cloning means field by field copying. such as string. • If the fields in turn are objects of another class. 2.

double S) { .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. salary and hireday. • In the above example. • As hireDay is a mutable object. • An example-Employee class with two fields-name and salary.the hireDay field is an object of Date class which is a mutable class. So must go for deep copy.the lifetime of the object (no method changing the value or yielding a reference) • Consider the Employee class with fields’ name. will be included when talking about deep cloning public class Employee implements Cloneable { public Employee(String n.

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

out. name=n. public class Employee implements Cloneable { public Employee() { salary=500.out.0 After Changing the Salary of Copy Object Original Object:Name=samSal=2000. Example import java. So needs Deep Cloning.0 Copy Object:NamesamSAl=2000.0 Copy Object:Name=samSal=2200. name=”xxx”.int y.*.getSalary()). { salary=s.double s. } } } Sample input and output Before Changing Original Object:Name=samSal=2000.println(e). Date Object is a Mutable Object.getName() +”sal=”+copy.println (“copu object:name=”+copy.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.util. . } catch(CloneNotSupportedException e) { system.00.System. } public Employee (String d).

} public double getSalary() { return(this.2000.20).hireday=(Date)hireday.7. } public Date getDate() { return hireday.salary).name). private double salary. } public String getName() { return(this. return cloned. . cloned.clone().hireday=newDate(new GregorianCalendar(y.m-1. } public void setDate() { hireday.getTimeInMillis()). try { Employee copy=original. } private String name.getTimeMillis()).7. private Date hireday.salary=salary+salary*percent/100.clone(). } public Employee clone() throws CloneNotSupportedException { Employee cloned=((Employee)super. } public void raiseSalary(int percent) { this.23).setTime(new GregorianCalender(2007. } public class EmployeeTest { public static void main(String args[]) { Employee original=new Employee(“sam”.2010.00.clone()).d).

System.getDate()). 1.0HireDayMon Aug 20 00:00:00 GMT+05:30 2007 Inner classes An inner class is a class that is defined inside another class.0HireDAyFri Jul 23 00 .println(“Copy Object:Name”+copy.They are. } } } Sample input & output Before changing Original Object:Name=samSal=2000.out. System.getName() +”sal=”+original.getDate()).0HireDayFri Jul 23 00:00:00:00 GMT+05:30 2010 Copy Object:NamesamSal=2000. Local inner classes that can access local variable of the enclosing scope .out.0HireDayFri Jul 23 00:00:00 GMT+05:30 2010 After Changing the Salary of Copy Object Original Object:Name=samSal=2000.println(“original object : Name=”+copy. 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.println(“Before Changing”).out.getSalary()+”HireDay=”+copy.System. Simple inner class-that acess an instance field of its outer class 2.getName() +”sal=”+copy.println(e).getSalary()+”HireDay=”+original. } catch(CloneNotSupportedException e) { System.00:00 GMT+05:30 2010 Copy Object:NamesamSal=2200.out.

outerDisplay(). • 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(). } } class OuterClass { . 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. obj. • The InnerClass contains a method DisplayOne(). Anonymouus inner classes and show how they are commonly used to implement callback 4.3. • This is possible because. • 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.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().

if only one method in the outer class wants too create object for the inner class.out.println(“the value of variable x is”+x). then instead of having it common for all methods. all the methods of the outer class can create objects for the inner class.println(“This is a simpler Inner Class “). • No method except the method containing the Inner class has any knowledge of the Inner class. • Suppose . Example program public class LocalInnerClassTest .private int x=1. • 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. System. • Consider an Outerclass contains a field x and a method outerDisplay(). public or private). public void outer Display() { InnerClass inn=new InnerClass(). • The Interclass contains a method DisplayOne() written inside outerDisplay(). can place it inside a method. inn.DisplayOne(). } class InnerClass { Public void DisplayOne() { System. • Local classes are never declared with an access specifies(that is.The outerclass outerclass() method creates an object for the InnerCLass and the InnerClass accesses the fields x of the outerclass.out. } } } Sample input & output This is simple inner class The value of variable X is 1 Local Inner Class • In simple inner class.

we can create any number of Objects for the innerclass.println(“the vqlue and variable X is”+x).DisplayOne(). System. inn.{ public static void main(String args[]) { OuterClass obj=new OuterClass(). } } InnerClass inn=new InnerClass().out.outerDisplay().the syntax is new Super Tpe(construction parameters) { . } } class OuterClass { private int x=1. obj.println(“this is a local inner class”).out. • If to make only a single object of a class. • Such a class is called an anonymous inner class In general. no need to give the class name. public void outerDisplay() { class InnerClass { public void DisplayOne() { System. } } Sample input & output This is a local Inner class The value of variable X is 1 Anonymous Inner Class • When using local inner classes.

the inner class implements that interface.out.inner class methods and data } • Here. } } interface Anon { public void displayAnon(). } .SuperType can be an interface:then. } } class OuterClass { private int x=1.out.println(“This is Anonmyous Inner Class”).println(“The value of x=”+x). System. public void displayAnonymous() { Anon inAnon=new Anon) { public void displayAnon() { System.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.displayAnonymous(). obj. • Or SuperType can be a class:then. } } inAnon.displayAnon().and the class has no name Example program public class ClassAnonTest { public static void main(String args[]) { OuterClassobj=newOuterClass().

• Of course.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. System.6.1. System.10.println(“The Maximum value=”+obj.MinMax(d).println(“The minimum value=”+obj.45}.12. • 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. • The minmax functions can then return an object of type pair.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.8.4.We can acieve that by defining a class pair that holds two values.Pair obj=Outerclass. write one method to compute the minimum and another method to compute the maximum.but don’t need the inner class to have a reference to the outer class object.computing both the minimum and the maximum simultaneously • However.getFirst()) would be more efficient to traverse the array only once.getSecond()).the method must return two numbers. • when you call both methods.then the array is traverser twice. } } class Outerclass { .

int max=values[0].max). for (int v:values) { if(min>v)min=v. second=s. } } Sample input &output The Minimum value=1. private int second. } public static Pair MinMax(int[] values) { int min=values[0].} private int first. The maximum value=45 Reflection • The reflection library gives a very rich and elaborate toolset to write programs that manipulates Java code dynamically.the components architecture for s) { first=f.public static class Pair { public Pair(int f.Can use it to • Analyze the capabilities of classes at runtime. . } public int getFirst(){return first. The reflection mechanism is extremely powerful. • Aprogram that can analyze the capabilities of classes is called reflective. if(max<v)max=v. } return new Pair(min.} public int getSecond(){return second. • this features is heavily used in JavaBeans.

• However. • This information keeps track of the class to which each object belongs.which returns the name of the class.then the Class Object can be created using gettClass().a Class object describes the properties of a particular class Three ways of creating an Object for Class 1. 2.the statement Class c=e. Can obtain a Class object corresponding to a class name by using the static forName method String className=” write a single to string method that workes for all classes.Date”. the Java runtime system always maintains what is called runtime type identification on all objects.getClass().Class The getClass method in the object class returns an instance of Class type Emplyee. .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.Then use getName().for example.For can also access this information by working with a special Java class. If the name of the object is known. The Class class • While program is running.getClass(). … Class cl=e. • implement generic array manipulation code.getName().util. • Just like an Employee object describes the properties of a particular employee. • The class that holds this information is called.• Insepct objects at runtime.

3.The three classes 1.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 .class is the matching class object.methods.Class cl=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. Using Reflection to Analyze the Capabilities of classes The most important part of the reflection mechanism is to examine the structure of a class.Method.Field 2.if T is any Java type.class.For example Class cl1=Date.and 3.lang.forName(className).then T.Constructor in the java. A third method for obtaining an object of type Class.reflect package describe the fields.and constructor of a class.

for (int i = 0. Method mtd[] = cl.println(mtd[i].out. // getFields() returns all the declared fields of the class. // getDeclaredFields() returns all the constructors of the class.out.length.println("Name of the Constructors of the String class"). import java.out.reflect.forName("java.lang.println(cnst[i]. } .out. i++) { System.println(fld[i].println("Name of the Declared fields"). i++) { System. System.Method.length. i < cnst. } System.reflect. for (int i = 0.getName()).lang.out. // getMethods() returns all the declared methods of the class.getMethods().out.getDeclaredFields().length. Constructor cnst[] = cl.Constructor. i < fld. 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.getConstructors().getName()).println("Name of the Methods"). for (int i = 0.lang.reflect.Field.getName()). import java. i++) { System. Field fld[] = cl. } System.Reflection example program import java.String").lang. i < mtd.

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