Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Programming paradigms


Published on

  • Be the first to comment

Programming paradigms

  2. 2. A.V.C College of Engineering Department of Computer Science & Engineering 2013 Odd Semester SYLLABUS CS2305 PROGRAMMING PARADIGMS L T P C 3 0 0 3 AIM: To understand the concepts of object-oriented, event driven, and concurrent programming paradigms and develop skills in using these paradigms using Java. UNIT I OBJECT-ORIENTED PROGRAMMING – FUNDAMENTALS 9 Review of OOP - Objects and classes in Java – defining classes – methods - access specifiers – static members – constructors – finalize method – Arrays – Strings - Packages – JavaDoc comments UNIT II OBJECT-ORIENTED PROGRAMMING – INHERITANCE 10 Inheritance – class hierarchy – polymorphism – dynamic binding – final keyword – abstract classes – the Object class – Reflection – interfaces – object cloning – inner classes – proxies UNIT III EVENT-DRIVEN PROGRAMMING 10 Graphics programming – Frame – Components – working with 2D shapes – Using color, fonts, and images - Basics of event handling – event handlers – adapter classes – actions – mouse events – AWT event hierarchy – introduction to Swing – Model-View- Controller design pattern – buttons – layout management – Swing Components UNIT IV GENERIC PROGRAMMING 8 Motivation for generic programming – generic classes – generic methods – generic code 2
  3. 3. and virtual machine – inheritance and generics – reflection and generics – exceptions – exception hierarchy – throwing and catching exceptions – Stack Trace Elements - assertions – logging UNIT V CONCURRENT PROGRAMMING 8 Multi-threaded programming – interrupting threads – thread states – thread properties – thread synchronization – thread-safe Collections – Executors – synchronizers – threads and event-driven programming TOTAL=45 PERIODS TEXT BOOK: 1. Cay S. Horstmann and Gary Cornell, “Core Java: Volume I – Fundamentals”, Eighth Edition, Sun Microsystems Press, 2008. REFERENCES: 1. K. Arnold and J. Gosling, “The JAVA programming language”, Third edition, Pearson Education, 2000. 2. Timothy Budd, “Understanding Object-oriented programming with Java”, Updated Edition, Pearson Education, 2000. 3. C. Thomas Wu, “An introduction to Object-oriented programming with Java”, Fourth Edition, Tata McGraw-Hill Publishing company Ltd., 2006. 3
  4. 4. CS2305 PROGRAMMING PARADIGMSnit No Title I Object-oriented Programming – Fundamentals II Object-oriented Programming – Inheritance III Event-Driven Programming IV Generic Programming V Concurrent Programming 4
  5. 5. CS2305 PROGRAMMING PARADIGMS UNIT I OBJECT-ORIENTED PROGRAMMING – FUNDAMENTALS 1) Review of OOP Concepts a) Encapsulation b) Inheritance c) Polymorphism 2) Objects and Classes in Java 3) Language Basics a) Comments b) Data Types c) Variables d) Statements e) Functions 4) Defining Classes 5) Methods 6) Access Specifiers 7) Static Members 8) Constructors a) Parameterized Constructors b) this Keyword c) Garbage Collection 9) Finalize Method 10) Arrays a) One Dimensional Arrays b) Multi Dimensional Arrays 11) Strings 12) Packages 13) JavaDOC Comments 14) References 1. Review OOP concepts The object oriented paradigm is built on the foundation laid by the structured programming concepts. • The fundamental change in OOP is that a program is designed around the data being operated upon rather upon the operations themselves. • Data and its functions are encapsulated into a single entity. • OOP facilitates creating reusable code that can eventually save a lot of work. • Polymorphism permits to create multiple definitions for functions. • Inheritance permits to derive new classes from old ones. Benefits of object oriented programming • Data security is enforced. • Inheritance saves time. • User defined data types can be easily constructed. © A.V.C College of Engineering
  6. 6. CS2305 PROGRAMMING PARADIGMS • Inheritance emphasizes inventions of new data types. • Large complexity in the software development can be easily managed. Java History Java is a general-purpose object oriented programming language developed by Sun Microsystems of USA in 1991. Originally called ―oak‖ by James Gosling, one of the inventors if the language. This goal had a strong impact on the development team to make the language simple, portable, highly reliable and powerful language. Java also adds some new features. While C++ is a superset of C. Java is neither a superset nor a subset of C or C++. C++ C Java Basic concepts of Object oriented programming • All Java programs are object oriented. Computer programs consist of two elements: code and data. • In process oriented model code acting on data. Procedural languages such as C employ this model. • To manage increasing complexity object-oriented Programming approach was conceived. Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code. Abstraction An essential element of object-oriented programming is abstraction. Abstraction refers to the act of representing essential features without including the background details or explanations. For example, people do not think of a car as a set of tens of thousands of individual parts. They think of it as a well-defined object with its own unique behavior. This abstraction allows people to use a car to drive to the grocery store without being overwhelmed by the complexity of the parts that form the car. They can ignore the details of how the engine, transmission, and braking systems work. Instead they are free to utilize the object as a whole. The Three OOP Principles All object-oriented programming languages provide mechanisms to implement the object-oriented model. They are • Encapsulation • Inheritance • Polymorphism © A.V.C College of Engineering
  7. 7. CS2305 PROGRAMMING PARADIGMS a) Encapsulation Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. For example, shifting gears does not turn on the headlights in car, because it encapsulates the information about all process. In Java the basis of encapsulation is the class. A class defines the structure and behavior (data and code) that will be shared by a set of objects. For this reason, objects are sometimes referred to as instances of a class. Thus, a class is a logical construct and an object has physical reality. b) Inheritance Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. For example Bird Attributes: Feathers Lay eggs Flying bird Attributes: ----------- ---------- Non flying bird Attributes: ----------- ----------- The bird 'robin ' is a part of the class 'flying bird' which is again a part of the class 'bird'. The concept of inheritance provides the idea of reusability. c) Polymorphism Polymorphism means the ability to take more than one form. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class. Shape Draw() Circle Object Draw() Box Object Draw() Triangle Object Draw()
  8. 8. 2. Class and Object Class defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is a template for an object, and an object is an instance of a class. Class A class is a blueprint or prototype from which objects are created. The entire set of data and code of an object can be made of a user defined data type with the help of a class. We can create any number of objects for the same class. © A.V.C College of Engineering
  9. 9. CS2305 PROGRAMMING PARADIGMS For example the construction of building requires a plan. Without plan we can't construct building. Here plan acts as class. Building acts as object. Using the same plan we can build any number of buildings. In the same way we can create any number of objects for the same class. Class tells the object’s state and behavior. Basically class tells what the object should have. Object Object is an instance of class. Object is real world entity which has state, identity and behavior. It may represent a person, a place, a bank account, a table of data or any item that the program has to handle. JAVA Program structure A file containing Java source code is considered a compilation unit. Such a compilation unit contains a set of classes and, optionally, a package definition to group related classes together. Classes contain data and method members that specify the state and behavior of the objects in your program. Java programs come in two flavors: 1. Standalone applications that have no initial context such as a pre-existing main window 2. Applets for WWW programming Execution begins when you launch the java virtual machine and tell it to find a particular class. After finding the class, java executes the enclosed main() method with signature: public static void main(String[] args) { ………... } Program Execution Create a source code file using a text editor. The source code is then compiled using the java compiler javac. Each java program is converted into one or more class files. The content of the class file is a set of instructions called bytecode to be executed by Java Virtual Machine (JVM).Java introduces bytecode to create platform independent program. JVM is an interpreter for bytecode which accepts java bytecode and produces result. Java Source Code Java Compiler (Javac) Java Byte Code (.class) Java Virtual Machine Java program Output © A.V.C College of Engineering
  10. 10. CS2305 PROGRAMMING PARADIGMS 3. Language Basics a) Comments Java comments make your code easy to understand, modify and use. Java supports three different types of comment styles. 1.Everything between initial slash –asterisk and ending asterisk-slash is ignored by the java compiler.(/*……*/) 2.Double slash (//)mark is ignored by java compiler. 3.Everything between initial slash – asterisk - asterisk and ending asterisk-slash is ignored by the java compiler and another program called JAVADOC.EXE that ships with the JDK uses these comments to construct HTML documentation files that describe your packages, classes and methods as well as all the variables used. (/**……*/) b) Data Types Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float, double, and boolean. These can be put in four groups: • Integers - This group includes byte, short, int, and long, which are for whole valued signed numbers. • Floating -point numbers- This group includes float and double, which represent numbers with fractional precision. • Characters - This group includes char, which represents symbols in a character set, like letters and numbers. • Boolean - This group includes boolean, which is a special type for representing true/false values. c) Variables Variables are locations in memory in which values can be stored. They have a name, a type, and a value. Before you can use a variable, you have to declare it. After it is declared, you can then assign values to it. Java actually has three kinds of variables: instance variables, class variables, and local variables. • Instance variables are used to define attributes or the state for a particular object.
  11. 11. • Class v ariables are similar to instance variables, except their values apply to all that class’s instances (and to the class itself) rather than having different values for each object. • Local variables are declared and used inside method definitions, for example, for index counters in loops, as temporary variables, or to hold values that you need only inside the method definition itself. Although all three kinds of variables are declared in much the same ways, class and instance variables are accessed and assigned in slightly different ways from local variables. Scope © A.V.C College of Engineering
  12. 12. CS2305 PROGRAMMING PARADIGMS • Java has no global variables. • All variables must be declared within either a class scope or a function scope. Declaring Variables For variable declarations, Java syntax is similar to C and C++ syntax. For native types, the syntax may be summarized as follows: • One word type name. • A list of variable names, separated by commas. • An optional initializer following each variable name. • Terminated by semicolon. The following are examples of variable declarations: • This line of Java code declares a 32-bit integer variable named i: int i; • This line declares two 32-bit integer variables named i and j: int i , j; • This line declares i and j as above and initializes them: int i=3, j=4; d) Statements Java, like C, is an expression-based language. Expressions must always appear in the context of statements. A statement consists of an expression followed by a terminating semicolon (;). Statements can be made up of zero or more expressions, provided that their combination makes syntactic sense. Expressions (except for the return value of void methods) have a value and a type. A terminating semicolon (e.g., 27;) turns it into a legal statement even though it does not do anything useful. A simple statement consists of an expression and a semicolon. The semicolon is a required terminator. 4. Defining Class The class is at the core of Java. It is the logical construct upon which the entire Java language is built because it defines the shape and nature of an object. As such, the class forms the basis for object-oriented programming in Java. The entire set of data and code of an object can be made of a user defined data type with the help of a class. Thus, a class is a template for an object, and an object is an instance of a class. The General Form of a Class The class contains data and the code that operates on that data. A class is declared by use of the class keyword. The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class. The general form of a class definition is shown here: class classname { type instance-variable1; type instance-variable2; © A.V.C College of Engineering
  13. 13. CS2305 PROGRAMMING PARADIGMS // ... type instance-variableN; type methodname1(parameter-list){ // body of method } type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) { // body of method } } Here is a class called Box that defines three instance variables: width, height, and depth. Currently, Box does not contain any methods (but some will be added soon). class Box { double width; double height; double depth; } Instantiating a class Class declaration only creates a template; it does not create an actual object. To create a Box object, you will use a statement like the following: Box mybox = new Box(); // create a Box object called mybox • The new operator allocates space for the new object, calls a class constructor and returns a reference to the object. • It should be noted that the class and its constructor have the same name. After this statement executes, mybox will be an instance of Box. Each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. Thus, every Box object will contain its own copies of the instance variables width, height, and depth. To access these variables, you will use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable. For example, to assign the width variable of mybox the value 100, you would use the following statement: mybox.width = 100; This statement tells the compiler to assign the copy of width that is contained within the mybox object the value of 100. 5. Methods Classes usually consist of two things: instance variables and methods. This is the general form of a method: Type name (parameter-list) © A.V.C College of Engineering
  14. 14. CS2305 PROGRAMMING PARADIGMS { // body of method } Type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. The name of the method is specified by name. This can be any legal identifier other than those already used by other items within the current scope. The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. Methods that have a return type other than void return a value to the calling routine using the following form of the return statement: return value; Here, value is the value returned. Program includes a method inside the box class. class Box { double width; double height; double depth; // display volume of a box void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // display volume of first box mybox1.volume(); // display volume of second box © A.V.C College of Engineering
  15. 15. CS2305 PROGRAMMING PARADIGMS mybox2.volume(); } } This program generates the following output. THE JAVA LANGUAGE Volume is 3000.0 Volume is 162.0 The mybox1.volume() invokes the volume( ) method on mybox1. That is, it calls volume( ) relative to the mybox1 object, using the object’s name followed by the dot operator. Thus, the call to mybox1.volume( ) displays the volume of the box defined by mybox1, and the call to mybox2.volume( ) displays the volume of the box defined by mybox2. Each time volume( ) is invoked, it displays the volume for the specified box. 6. Access specifiers Encapsulation provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. How a member can be accessed is determined by the access specifier that modifies its declaration. Java supplies a rich set of access specifiers. Some aspects of access control are related mostly to inheritance or packages. (A package is, essentially, a grouping of classes.) Java’s access specifiers are  Public  Private  Protected  default access level. Public When a member of a class is modified by the public specifier, then that member can be accessed by any other code. So main( ) has always been preceded by the public specifier. Classes can be declared public. A public class is accessible by any other Java class. A class that is not declared public has package access, which means that only classes within the same package may access it. Class members labeled public are accessible to all other classes. Private When a member of a class is specified as private, then that member can only be accessed by other members of its class. Class members can be declared public or private to enforce proper encapsulation. Certain data elements or methods that are necessary for the class’s internal behavior should be protected from access by outside classes. These should be declared private. 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. Protected Any member that is declared protected is accessible only by a class that is derived from the current class or is in the same package as the containing class. © A.V.C College of Engineering
  16. 16. CS2305 PROGRAMMING PARADIGMS default access level When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package. 7. Static Members Static Variables If you define a field as static, then there is only one such field per class. In contrast, each object has its own copy of all instance fields. For example, let's suppose we want to assign a unique identification number to each employee. We add an instance field id and a static field nextId to the Employee class: class Employee { ... private int id; private static int nextId = 1; } Now, every employee object has its own id field, but there is only one nextId field that is shared among all instances of the class. Let's put it another way. If there are one thousand objects of the Employee class, then there are one thousand instance fields id, one for each object. But there is a single static field nextId. Even if there are no employee objects, the static field nextId is present. It belongs to the class, not to any individual object. Constants
  17. 17. Static variables are quite rare. However, static constants are more common. For example, the Math class defines a static constant: public class Math { ... public static final double PI = 3.14159265358979323846; © A.V.C College of Engineering
  18. 18. CS2305 PROGRAMMING PARADIGMS ... } You can access this constant in your programs as Math.PI. If the keyword static had been omitted, then PI would have been an instance field of the Math class. That is, you would need an object of the Math class to access PI, and every object would have its own copy of PI. Another static constant that you have used many times is System.out. It is declared in the System class as: public class System { ... public static final PrintStream out = . . .; ... } As we mentioned several times, it is never a good idea to have public fields because everyone can modify them. However, public constants (that is, final fields) are ok. Since out has been declared as final, you cannot reassign another print stream to it: out = new PrintStream(. . .); // ERROR--out is final Static Methods Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method. The expression: Math.pow(x, y) Computes the power xy. It does not use any Math object to carry out its task. In other words, it has no implicit parameter. In other words, you can think of static methods as methods that don't have a this parameter. Because static methods don't operate on objects, you cannot access instance fields from a static method. But static methods can access the static fields in their class. Here is an example of such a static method: public static int getNextId() { return nextId; // returns static field } To call this method, you supply the name of the class: int n = Employee.getNextId(); Could you have omitted the keyword static for this method? Yes, but then you would need to have an object reference of type Employee to invoke the method. You use static methods in two situations: 1. When a method doesn't need to access the object state because all needed parameters are supplied as explicit parameters (example: Math.pow) 2. When a method only needs to access static fields of the class (example: Employee.getNextId) 8. Constructors A constructor is a special method whose purpose is to construct and initialize objects. Constructors always have the same name as the class name. The constructor is automatically called immediately after the object is created, before the new operator completes. Box mybox1 = new Box(); © A.V.C College of Engineering
  19. 19. CS2305 PROGRAMMING PARADIGMS new Box( ) is calling the Box( ) constructor. When you do not explicitly define a constructor for a class, then Java creates a default constructor for the class. The default constructor automatically initializes all instance variables to zero. There is an important difference between constructors and other methods: A constructor can only be called in conjunction with the new operator. You can't apply a constructor to an existing object to reset the instance fields. Features of constructor  A constructor has the same name as the class.  A class can have more than one constructor.  A constructor may take zero, one, or more parameters.  A constructor has no return value.  A constructor is always called with the new operator. a) Parameterized Constructors Add parameters to the constructor. class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo7 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); } } The output from this program is shown here: Volume is 3000.0 © A.V.C College of Engineering
  20. 20. CS2305 PROGRAMMING PARADIGMS Object is initialized as specified in the parameters to its constructor. Box mybox1 = new Box(10, 20, 15); The values 10, 20, and 15 are passed to the Box( ) constructor when new creates the object. Thus, mybox1’s copy of width, height, and depth will contain the values 10, 20, and 15, respectively. b) “this” Keyword this can be used inside any method to refer to the current object. this keyword has two meanings:  to denote a reference to the implicit parameter  to call another constructor of the same class. // A redundant use of this. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } c) Garbage Collection The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 9. Finalizer method Finalizer methods are like the opposite of constructor methods; whereas a constructor method is used to initialize an object, finalizer methods are called just before the object is garbage collected and its memory reclaimed. To create a finalizer method, include a method with the following signature in your class definition: void finalize() { ... } Inside the body of that finalize() method, include any cleaning up you want to do for that object. Before you start using finalizer methods extensively in your Java programs, however, be aware that finalizer methods have several very important restrictions. First of all, the finalizer method is not guaranteed to be called until the object’s memory is actually reclaimed, which may be some time after you’ve removed all references to that object. However, calling finalize() does not trigger an object to be garbage-collected. Only removing all references to an object will cause it to be marked for deleting, and even then, Java may or may not call the finalize() method itself—regardless of whether or not you’ve already called it. Finalizer methods are best used for optimizing the removal of an object—for example, by removing references to other objects, by cleaning up things that object may have touched, or for other optional behaviors that may make it easier for that object to be removed. In most cases, you may not need to use finalize() at all. © A.V.C College of Engineering
  21. 21. CS2305 PROGRAMMING PARADIGMS Some object-oriented programming languages, notably C++, have explicit destructor methods for any cleanup code that may be needed when an object is no longer used. The most common activity in a destructor is reclaiming the memory set aside for objects. Since Java does automatic garbage collection, manual memory reclamation is not needed, and Java does not support destructors. Of course, some objects utilize a resource other than memory, such as a file or a handle to another object that uses system resources. In this case, it is important that the resource be reclaimed and recycled when it is no longer needed. You can add a finalize method to any class. The finalize method will be called before the garbage collector sweeps away the object. In practice, do not rely on the finalize method for recycling any resources that are in short supply—you simply cannot know when this method will be called. If a resource needs to be closed as soon as you have finished using it, you need to manage it manually. Add a dispose method that you call to clean up what needs cleaning. Just as importantly, if a class you use has a dispose method, you will want to call it when you are done with the object. In particular, if your class has an instance field that has a dispose method, provide a dispose method that disposes of the instance fields. 10. Arrays An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information. Arrays are ordered collections of identical objects that can be accessed via an index. Java arrays have their own behavior that is encapsulated into their definition when the compiler creates them. Since arrays are objects, array variables behave like class-type variables. It is important to distinguish between the array variable and the array instance to which it refers. • Declaring an array only declares the array variable. • To instantiate the array, the new operator must be used with the [] operator to enclose the array size. The array size can be any integer expression. The following code declares an array variable and initializes it to null: char data[] = null; Array Constants The declaration of an array must include its type, but not its size. An array initializer is either a new expression that evaluates to the correct array type, or a list of initial element values enclosed in { }. The following array constant provides initial values for its elements: int[] int_array = {1, 3, 4, 15, 0}; Using Arrays Array elements can be accessed using an index in square brackets [n], where the index must be an integer. Arrays start with index number 0, not 1. The index can be thought of as an offset from the beginning of the array. The index may not be less than zero or greater than the declared size. If the array is declared size n, the index must be in the range 0 to n-1. Any attempt to index an array with an illegal value will cause an exception to be thrown. All arrays have a data field called length that indicates its size. int ia[] = new int[100]; for (int i = 0; i < ia.length; i++) { © A.V.C College of Engineering
  22. 22. CS2305 PROGRAMMING PARADIGMS ia[i] = i * i; } Copying Array Elements The library method System.arraycopy() is useful for copying a number of elements from one array to another. The method can be used on any type of array and is declared as follows: public static void arraycopy (Object src, int src_position, Object dst, int dst_position, int length) The method copies elements from the given source array, beginning at the specified position to the destination array at the specified position. It copies the number of elements specified by the length argument. The destination array must already be allocated. Any type of array may be copied. If range exceeds bounds of either array, a run-time error results. Arrays in Java are in between a class and a data type although they are implemented as a class internally by Java. char data[] = null; char[] data = null; int length = 60; char[] data = new char [length]; a) One-Dimensional Arrays A one-dimensional array is a list of like-typed variables. Array is created by following steps. 1. Create an array variable of the desired type. The general form of a one dimensional array declaration is type var-name[ ]; 2. Allocate memory for array. Method1: The general form of new as it applies to one-dimensional arrays appears as follows: array-var = new type[size]; The elements in the array allocated by new will automatically be initialized to zero. Method2: Arrays can be initialized when they are declared. The process is much the same as that used to initialize the simple types. An array initializer is a list of comma- separated expressions surrounded by curly braces. The commas separate the values of the array elements. The array will automatically be created large enough to hold the number of elements you specify in the array initializer. There is no need to use new. For example, to store the number of days in each month, the following code creates an initialized array of integers: // An improved version of the previous program. class AutoArray { public static void main(String args[]) { int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 }; System.out.println("April has " + month_days[3] + " days."); } } © A.V.C College of Engineering
  23. 23. CS2305 PROGRAMMING PARADIGMS b) Multidimensional Arrays In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look and act like regular multidimensional arrays. However, as you will see, there are a couple of subtle differences. To declare a multidimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two- dimensional array variable called twoD. int twoD[][] = new int[4][5]; This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int. There is a second form that may be used to declare an array: type[ ] var-name; Here, the square brackets follow the type specifier, and not the name of the array variable. For example, the following two declarations are equivalent: int al[] = new int[3]; int[] a2 = new int[3]; The following declarations are also equivalent 11. String objects The Java String class (java.lang.String) is a class of object that represents a character array of arbitrary length. While this external class can be used to handle string objects, Java integrates internal, built-in strings into the language.
  24. 24. © A.V.C College of Engineering
  25. 25. CS2305 PROGRAMMING PARADIGMS An important attribute of the String class is that once a string object is constructed, its value cannot change (note that it is the value of an object that cannot change, not that of a string variable, which is just a reference to a string object). All String data members are private, and no string method modifies the string’s value. String Methods Although a string represents an array, standard array syntax cannot be used to inquire into it. These are detailed in the below Table. String Comparison String comparison methods listed in below Table.
  26. 26. © A.V.C College of Engineering
  27. 27. CS2305 PROGRAMMING PARADIGMS String Searching The String class also provides methods that search a string for the occurrence of a single character or substring. These return the index of the matching substring or character if found, or - 1 if not found.  int indexOf (char ch)  int indexOf (char ch, int begin)  int lastIndexOf (char ch)  int lastIndexOf (char ch, int fromIndex)  int indexOf (String str)  int indexOf (String str, int begin)  int lastIndexOf (String str)  int lastIndexOf (String str, int fromIndex) The following example shows the usage of these functions: if (s1.indexOf (’:’) >= 0) { … } String suffix =
  28. 28. s1.substring (s1.lastIndexOf (’.’)); int spaceCount = 0; int index = s1.indexOf (’ ’); while (index >= 0) { ++spaceCount; index = s1.indexOf (’ ’, index + 1); © A.V.C College of Engineering
  29. 29. CS2305 PROGRAMMING PARADIGMS } int index = s1.indexOf (―that );‖ String Concatenation The String class provides a method for concatenating two strings: String concat (String otherString) The + and += String operators are more commonly used: The Java compiler recognizes the + and += operators as String operators. For each + expression, the compiler generates calls to methods that carry out the concatentation. For each += expression, the compiler generates calls to methods that carry out the concatenation and assignment. Converting Objects To Strings The String + operator accepts a non-string operand, provided the other operand is a string. The action of the + operator on non-string operands is to convert the non-string to a string, then to do the concatenation. Operands of native types are converted to string by formatting their values. Operands of class types are converted to a string by the method toString() that is defined for all classes. Any object or value can be converted to a string by explicitly using one of the static valueOf() methods defined in class String: String str = String.valueOf (obj); If the argument to valueOf() is of class type, then valueOf() calls that object’s toString() method. Any class can define its own toString() method, or just rely on the default. The output produced by toString() is suitable for debugging and diagnostics. It is not meant to be an elaborate text representation of the object, nor is it meant to be parsed. These conversion rules also apply to the right-hand side of the String += operator. Converting Strings To Numbers Methods from the various wrapper classes, such as Integer and Double, can be used to convert numerical strings to numbers. The wrapper classes contain static methods such as parseInt() which convert a string to its own internal data type. 12. Packages Java allows you to group classes in a collection called a package. A class can use all classes from its own package and all public classes from other packages. You can import a specific class or the whole package. You place import statements at the top of your source files (but below any package statements). For example, you can import all classes in the java.util package with the statement: import java.util.*; Adding a class into a package To place classes inside a package, you must put the name of the package at the top of your source file, before the code that defines the classes in the package. For example, package com.horstmann.corejava; public class Employee © A.V.C College of Engineering
  30. 30. CS2305 PROGRAMMING PARADIGMS { ... } Package scope • Public features can be used by any class. • Private features can only be used by the class that defines them. • If you don't specify either public or private, then the feature (that is, the class, method, or variable) can be accessed by all methods in the same package. 13. Documentation Comments The Java SDK contains a very useful tool, called javadoc, that generates HTML documentation from your source files. If you add comments that start with the special delimiter /** to your source code, you too can produce professional-looking documentation easily. This is a very nice scheme because it lets you keep your code and documentation in one place. If you put your documentation into a separate file, then you probably know that the code and comments tend to diverge over time. But since the documentation comments are in the same file as the source code, it is an easy matter to update both and run javadoc again. How to Insert Comments The javadoc utility extracts information for the following items: • Packages • Public classes and interfaces • Public and protected methods • Public and protected fields You can (and should) supply a comment for each of these features. Each comment is placed immediately above the feature it describes. A comment starts with a /** and ends with a */. Each /** . . . */ documentation comment contains free-form text followed by tags. A tag starts with an @, such as @author or @param. The first sentence of the free-form text should be a summary statement. The javadoc utility automatically generates summary pages that extract these sentences. In the free-form text, you can use HTML modifiers such as <em>...</em> for emphasis, <code>...</code> for a monospaced ―typewriter‖ font, <strong>...</strong> for strong emphasis, and even <img ...> to include an image. You should, however, stay away from heading <h1> or rules <hr> since they can interfere with the formatting of the document. Class Comments The class comment must be placed after any import statements, directly before the class definition. Here is an example of a class comment: /** A <code>Card</code> object represents a playing card, such as "Queen of Hearts". A card has a suit (Diamond, Heart, Spade or Club) and a value (1 = Ace, 2 . . . 10, 11 = Jack, 12 = Queen, 13 = King). */ public class Card © A.V.C College of Engineering
  31. 31. CS2305 PROGRAMMING PARADIGMS { ... } Method Comments Each method comment must immediately precede the method that it describes. In addition to the general-purpose tags, you can use the following tags: @param variable description This tag adds an entry to the ―parameters‖ section of the current method. The description can span multiple lines and can use HTML tags. All @param tags for one method must be kept together. @return description This tag adds a ―returns‖ section to the current method. The description can span multiple lines and can use HTML tags. @throws class description Field Comments You only need to document public fields—generally that means static constants. For example, /** The "Hearts" card suit */ public static final int HEARTS = 1; General Comments The following tags can be used in class documentation comments. @author name This tag makes an ―author‖ entry. You can have multiple @author tags, one for each author. @version text How to Extract Comments Here, docDirectory is the name of the directory where you want the HTML files to go. Follow these steps: 1. Change to the directory that contains the source files you want to document. If you have nested packages to document, such as com.horstmann.corejava, you must be in the directory that contains the subdirectory com. (This is the directory that contains the overview.html file, if you supplied one.) 2. Run the command javadoc -d docDirectory nameOfPackage for a single package. Or run javadoc -d docDirectory nameOfPackage1 nameOfPackage2... to document multiple packages. If your files are in the default package, then run javadoc -d docDirectory *.java instead. If you omit the -d docDirectory option, then the HTML files are extracted to the current directory. That can get messy, and we don't recommend it. The javadoc program can be fine-tuned by numerous command-line options. For example, you can use the - author and -version options to include the @author and @version tags in the documentation. (By default, they are omitted.) © A.V.C College of Engineering
  32. 32. CS2305 PROGRAMMING PARADIGMS 14. References 1. Cay S. Horstmann and Gary Cornell, ―Core Java: Volume I – Fundamentals ,‖ Eighth Edition, Sun Microsystems Press, 2008. 2. Herbert Schildt ―JAVA2:The complete reference‖ Fifth Edition, McGraw-Hill/Osborne. 3.
  33. 33. © A.V.C College of Engineering
  34. 34. CS2305 PROGRAMMING PARADIGMS UNIT II OBJECT-ORIENTED PROGRAMMING – INHERITANCE 1. Inheritance 1.1. Member Access And Inheritance 1.2. Super Keyword 2. Class Hierarchy 3. Polymorphism 3.1. Overridden Methods 3.2. Overloaded Methods 4. Dynamic Binding 4.1. Dynamic Binding 4.2. Static Binding 5. Final Keyword 6. Abstract Classes 6.1. Abstract Methods 7. The Object Class 8. Reflection 9. Interfaces 10. Object Cloning 11. Inner Classes 12. Proxies 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. © A.V.C College of Engineering
  35. 35. CS2305 PROGRAMMING PARADIGMS 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 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. 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. © A.V.C College of Engineering
  36. 36. CS2305 PROGRAMMING PARADIGMS 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{ 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. 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. © A.V.C College of Engineering
  37. 37. CS2305 PROGRAMMING PARADIGMS 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. 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"); } } © A.V.C College of Engineering
  38. 38. CS2305 PROGRAMMING PARADIGMS Output Hai 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"); } } 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:
  39. 39. 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. © A.V.C College of Engineering
  40. 40. CS2305 PROGRAMMING PARADIGMS 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 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 variables. Attempts to change it will generate either a compile-time error or an exception. © A.V.C College of Engineering
  41. 41. CS2305 PROGRAMMING PARADIGMS 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. 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. © A.V.C College of Engineering
  42. 42. CS2305 PROGRAMMING PARADIGMS 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 …….. } 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."); } } 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 © A.V.C College of Engineering
  43. 43. CS2305 PROGRAMMING PARADIGMS 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. To declare an abstract method, use this general form: abstract type name(parameter-list); UAGE 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. To make a class implement an interface, have to carry out two steps: © A.V.C College of Engineering
  44. 44. CS2305 PROGRAMMING PARADIGMS  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. 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 , 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. © A.V.C College of Engineering
  45. 45. CS2305 PROGRAMMING PARADIGMS 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); } } 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(); mi.display(); } public static void main(String arg[]){ MyOuter mo = new MyOuter(); mo.inner(); } } © A.V.C College of Engineering
  46. 46. CS2305 PROGRAMMING PARADIGMS 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(); } } 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 , 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. © A.V.C College of Engineering
  47. 47. CS2305 PROGRAMMING PARADIGMS  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); } } } 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 © A.V.C College of Engineering
  48. 48. CS2305 PROGRAMMING PARADIGMS  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. Java.lang.Class Field[] getFields() Method[] getMethods() Constructor[] getConstructors() Return an array of public fields, methods and constructors that the class supports. This includes all public members of super class. Field[] getDeclaredFields() Method[] getDeclaredMethods() Constructor[] getDeclaredConstructors() Return an array of fields, methods and constructors that are declared in the class. This includes private, protected and public members of class but not members of super class. Java.lang.reflect Field Method Constructor Methods (Field, Method & Constructor): • String getName() – return the name of the item. • int getModifiers()- return an integer, that describes the modifier. Field
  49. 49. • 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.*; © A.V.C College of Engineering
  50. 50. CS2305 PROGRAMMING PARADIGMS class Test{ public int var1; private int var2; protected int var3; int var4; } 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 • 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() {} } © A.V.C College of Engineering
  51. 51. CS2305 PROGRAMMING PARADIGMS 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()); 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
  52. 52. © A.V.C College of Engineering
  53. 53. CS2305 PROGRAMMING PARADIGMS Constructor • Provide information about constructors • 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"); 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 © A.V.C College of Engineering
  54. 54. CS2305 PROGRAMMING PARADIGMS 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 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); arr = (int[])arrayGrow(arr); System.out.println(arr.length); } } Output: 10 20 Object cloning © A.V.C College of Engineering
  55. 55. CS2305 PROGRAMMING PARADIGMS • 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(); 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 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. © A.V.C College of Engineering
  56. 56. CS2305 PROGRAMMING PARADIGMS 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.
  57. 57. © A.V.C College of Engineering
  58. 58. CS2305 PROGRAMMING PARADIGMS Unit III Event-Driven Programming Graphics programming Frame Frame is a top-level window that has a title bar, menu bar, borders, and resizing corners. By default, a frame has a size of 0 × 0 pixels and it is not visible. Frames are examples of containers. It can contain other user interface components such as buttons and text fields. Class hierarchy for Frame Java.awt Component Container Window Frame Component & Window class Methods java.awt.Component • void setVisible(boolean b) - shows or hides the component depending on whether b is true or false. • void setSize(int width, int height) - resizes the component to the specified width and height. • void setBounds(int x, int y, int width, int height) - moves and resizes this component. The location of the top-left corner is given by x and y, and the new size is given by the width and height parameters. • void setBackground(java.awt.Color) – set Background color to the window. • void setForeground(java.awt.Color)- set Foreground color to the window. • void repaint() - causes a repaint of the component ―as soon as possible.‖ © A.V.C College of Engineering
  59. 59. CS2305 PROGRAMMING PARADIGMS java.awt.Window • void setTitle(String s) - sets the text in the title bar for the frame to the string s. Frame’s constructors: Frame( ) - creates a standard window that does not contain a title. Frame(String title) - creates a window with the title specified by title Methods of Frame class: • void setSize(int newWidth, int newHeight) - method is used to set the dimensions of the window. The dimensions are specified in terms of pixels. • void setVisible(boolean visibleFlag)- The component is visible if the argument to this method is true. Otherwise, it is hidden. • void setTitle(String newTitle)- change the title in a frame window. Creating a Frame Window Method 1: In main() method  Create an instance of a Frame class. Frame f=new Frame(―frame name );‖  Set the frame size f.setSize(500,500);  Make the frame visible f.setVisible(true); Example: The following java program creates a frame with the dimension as 600 x 400 and makes it visible in the screen. Import java.awt package because Frame class is available in that package. import java.awt.*; public class Demo{ public static void main(String arg[]){ Frame f=new Frame("Demo"); f.setSize(600,400); f.setVisible(true); } } Out Put: © A.V.C College of Engineering
  60. 60. CS2305 PROGRAMMING PARADIGMS Method :2 • Create a subclass of Frame. • In the Subclass constructor  Change the frame title by calling superclass [Frame] constructor using super(String) method call.  Set the size of the window explicitly by calling the setSize( ) method.  Make the frame visible by calling setVisible() method. • In main() method  Create an instance of subclass. Example: The following java program creates a frame with the dimension as 600 x 400 and makes it visible in the screen. Import java.awt package because Frame class is available in that package. import java.awt.*; public class Demo extends Frame{ Demo(String s){ super(s); setSize(600,400); setVisible(true); } Out Put: } public static void main(String arg[]){ Demo ob=new Demo("Demo"); } Working with 2D shapes Graphics: java.awt.Graphics The Graphics class is part of the java.awt package. The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled. Objects are drawn and filled in the currently selected graphics color, which is black by default. When a graphics object is drawn that exceeds the dimensions of the window, output is automatically clipped. Java Coordinate System Java’s coordinate system has the origin (0, 0) in the top left corner. Positive x values are to the © A.V.C College of Engineering
  61. 61. CS2305 PROGRAMMING PARADIGMS right, and positive y values are down. Coordinate units are measured in pixels (picture element). All pixel values are integers; there are no partial or fractional pixels. X coordinate: Horizontal distance moving right from the left of the screen. Y coordinate: Vertical distance moving from top to bottom of the screen. The Graphics class provides a set of simple built-in graphics primitives for drawing, including lines, rectangles, polygons, ovals, and arcs. Lines To draw straight lines, use the drawLine method. drawLine takes four arguments: the x and y coordinates of the starting point and the x and y coordinates of the ending point. • void drawLine(int startX, int startY, int endX, int endY) - displays a line in the current drawing color that begins at startX,startY and ends at endX,endY. Example: import java.awt.*; public class Demo extends Frame{ Demo(String s){ super(s); setSize(100,100); setVisible(true); } public void paint(Graphics g) { g.drawLine(10,10,60,60); } public static void main(String arg[]){ Demo ob=new Demo("Line Demo"); } }
  62. 62. Output: © A.V.C College of Engineering
  63. 63. CS2305 PROGRAMMING PARADIGMS Rectangles The Java graphics primitives provide two kinds of rectangles: Plain rectangles and Rounded rectangles(which are rectangles with rounded corners). • void drawRect(int x, int y, int width, int height) • void fillRect(int x, int y, int width, int height) • void drawRoundRect(int x, int y, int width, int height, int xDiam, int yDiam) • void fillRoundRect(int x, int y, int width, int height, int xDiam, int yDiam) A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at x, y. The dimensions of the rectangle are specified by width and height. The diameter of the rounding arc along the X axis is specified by xDiam. The diameter of the rounding arc along the Y axis is specified by yDiam. Example: import java.awt.*; Demo ob=new Demo("Line Demo"); public class Demo extends Frame{ Demo(String s){ super(s); setSize(500,500); setVisible(true); } public void paint(Graphics g) { g.drawRect(100,100,60,60); g.fillRect(250,100,60,60); g.drawRoundRect(100,250,60,60,10,10); g.fillRoundRect(250,250,60,60,20,20); } public static void main(String arg[]){ } } Output:
  64. 64. © A.V.C College of Engineering
  65. 65. CS2305 PROGRAMMING PARADIGMS Polygons Polygons are shapes with an unlimited number of sides. Set of x and y coordinates are needed to draw a polygon, and the drawing method starts at one, draws a line to the second, then a line to the third, and so on. • void drawPolygon(int x[ ], int y[ ], int numPoints) • void fillPolygon(int x[ ], int y[ ], int numPoints) x[]- An array of integers representing x coordinates y[]- An array of integers representing y coordinates numPoints- An integer for the total number of points Example: import java.awt.*; public class Demo extends Frame{ public void paint(Graphics g) { int x1[] = { 39,94,97,112,53,58,26 }; int y1[] = { 133,174,136,170,208,180,206 }; g.drawPolygon(x1,y1,7); int x2[] = { 139,194,197,212,153,158,126 }; int y2[] = { 133,174,136,170,208,180,206 }; g.fillPolygon(x2,y2,7); } public static void main(String arg[]){ Demo ob=new Demo("Polygon Demo"); } } Output:
  66. 66. © A.V.C College of Engineering
  67. 67. CS2305 PROGRAMMING PARADIGMS Ovals Use ovals to draw ellipses or circles. • void drawOval(int top, int left, int width, int height) • void fillOval(int top, int left, int width, int height)
  68. 68. © A.V.C College of Engineering
  69. 69. CS2305 PROGRAMMING PARADIGMS import java.awt.*; public class Demo extends Frame{ } } Demo(String s){ super(s); setSize(300,300); setVisible(true); } public void paint(Graphics g) { g.drawOval(20,120,70,70); g.fillOval(140,120,100,70); } public static void main(String arg[]){ Demo ob=new Demo("Oval Demo"); Arc The arc is drawn from startAngle through the angular distance specified by arkAngle. Angles are specified in degrees. The arc is drawn counterclockwise if sweepAngle is positive, and clockwise if arkAngle is negative. • void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) • void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) x=0 y=0 width=100 height=100 Startangle=90 arcAngle=180
  70. 70. © A.V.C College of Engineering
  71. 71. import java.awt.*; public class Demo extends Frame{ Demo(String s){ super(s); setSize(300,300); setVisible(true); CS2305 PROGRAMMING PARADIGMS } } Output: } public void paint(Graphics g) { g.drawArc(20,120,90,90,90,180); g.fillArc(120,120,90,90,90,180); g.drawArc(170,120,90,90,90,-180); } public static void main(String arg[]){ Demo ob=new Demo("Arc Demo"); Drawing Text Draw text on the screen using the method drawstring(). • void drawstring(String text, int x, int y)- draws a string in the current font and color. import java.awt.*; public class Demo extends Frame{ Demo(String s){ super(s); setSize(200,200); setVisible(true); } public void paint(Graphics g) { g.drawString("welcome", 75, 100); } public static void main(String arg[]){ Demo ob=new Demo("Text Demo"); } }
  72. 72. © A.V.C College of Engineering
  73. 73. CS2305 PROGRAMMING PARADIGMS Using color, fonts, and images Color: java.awt.Color Color class creates a solid RGB color with the specified red, green, blue value in the range (0- 255). Java’s abstract color model uses 24-bit color. The values of each color must be in the range (0- 255). Constructor: Color(int red, int green, int blue) - create new color object for any combination of red, green, and blue. Java.awt.Color class used to create new color object for any combination of red, green, and blue, and it predefines a few color constants. They are stored in class variables, Color.white (255,255,255) (0,0,0) Color.lightGray (192,192,192) Color.gray (128,128,128) Color.darkGray (64,64,64) (255,0,0) (0,0,255) Color.yellow (255,255,0) Color.magenta (255,0,255) Color.cyan( 0,255,255) (255,175,175) (255,200,0),255,0) java.awt.Component Component class defines setBackground() and setForeground() methods for setting background and foreground colors to the window. Since Frame is a subclass of Component class it can use these methods. • void setBackground(java.awt.Color) – set Background color to the window. • void setForeground(java.awt.Color)- set Foreground color to the window. java.awt.Graphics setColor() method used to set the current color for the graphics context which is defined in Graphics class. • void setColor(java.awt.Color) © A.V.C College of Engineering
  74. 74. CS2305 PROGRAMMING PARADIGMS Example: The following program for designing a frame with square boxes, each of which has a randomly chosen color in it. Demo ob=new Demo("Color Demo"); import java.awt.*; public class Demo extends Frame{ Demo(String s){ } } Output: super(s);setSize(200,200);setVisible(true); setBackground(; } public void paint(Graphics g) { int rval, gval, bval; for (int j = 30; j < 200-30; j += 30) for (int i = 30; i < 200-30; i+= 30){ rval = (int)Math.floor(Math.random() * 256); gval = (int)Math.floor(Math.random() * 256); bval = (int)Math.floor(Math.random() * 256); g.setColor(new Color(rval,gval,bval)); g.fillRect(i,j,25,25); } } public static void main(String arg[]){ Font: java.awt.Font Font class is used to create Font Objects to set the font for drawing text, labels, textField, buttons etc.., One Font constructor has this general form: Font(String fontName, int fontStyle, int pointSize) Here, fontName specifies the name of the desired font. The style of the font is specified by fontStyle. It may consist of one or more of thesethree constants: Font.PLAIN, Font.BOLD, and Font.ITALIC. The size, in points, of the font is specified by pointSize. point size may or may not be the height of the characters. To draw characters in a font, first create an object of the class Font. then specify the font name, the font style, and the point size. © A.V.C College of Engineering
  75. 75. CS2305 PROGRAMMING PARADIGMS Methods Java.awt.Graphics • void setFont(Font fontObj)- selects a font for the graphics context. That font will be used for subsequent text drawing operations. • Font getFont( )- get the current font by calling getFont( ). Java.awt.Component • void setFont(Font fontObj) Example: The following program that draws several lines of text in different fonts. import java.awt.*; public class Demo extends Frame{ Demo(String s){ super(s);setSize(200,200);setVisible(true); } public void paint(Graphics g) { Font f = new Font("TimesRoman", Font.PLAIN, 18); Font fb = new Font("TimesRoman", Font.BOLD, 18); Font fi = new Font("TimesRoman", Font.ITALIC, 18); Font fbi = new Font("TimesRoman", Font.BOLD + Font.ITALIC, 18); g.setFont(f); g.drawString("This is a plain font", 10, 50); g.setFont(fb); g.drawString("This is a bold font", 10, 75); g.setFont(fi); g.drawString("This is an italic font", 10, 100); g.setFont(fbi); g.drawString("This is a bold italic font", 10, 125); public static void main(String arg[]){ Demo ob=new Demo("Font Demo"); } } Output: } Image: java.awt.Image Image class provides support for displaying and manipulation of graphical images. Image is simply a rectangular graphical object.
  76. 76. © A.V.C College of Engineering
  77. 77. CS2305 PROGRAMMING PARADIGMS Java provides the functions for reading images that are stored in local files and display them on graphics object. Step1: Loading an image java.awt.Toolkit • Toolkit getDefaultToolkit()- returns the default toolkit. • Image getImage(String filename) - returns an image that will read its pixel data from a file. Toolkit object can only read GIF and JPEG files. Step2: displaying an image java.awt.Graphics • boolean drawImage(Image img, int x, int y, ImageObserver observer)- draws a scaled image. • boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) - draws a scaled image. The system scales the image to fit into a region with the given width and height. Note: This call may return before the image is drawn. Example: the following program draws a tiled graphics image from the top-left corner to bottom right corner of the window. import java.awt.*; public class Demo extends Frame{ Demo(String s){ super(s);setSize(300,300);setVisible(true); } public void paint(Graphics g) { Toolkit tk = Toolkit.getDefaultToolkit(); Image img= tk.getImage("E:/Sample/ball.jpg"); for (int i = 20; i <300-20; i=i+20) for (int j = 40; j <300-20; j=j+20) g.drawImage(img,i,j,20,20,null); } public static void main(String arg[]){ Demo ob=new Demo("Image Demo"); } } Output: © A.V.C College of Engineering
  78. 78. CS2305 PROGRAMMING PARADIGMS Component Constructor Methods Label Label( ) Label(String str) Label(String str, int how) void setText(String str) String getText( ) Button Button( ) Button(String str) void setLabel(String str) String getLabel( ) List List( ) List(int numRows) List(int numRows, boolean multipleSelect) void add(String name) void add(String name, int index) String getSelectedItem( ) int getSelectedIndex( ) String[ ] getSelectedItems( ) Choice Choice( ) void add(String name) String getSelectedItem( ) int getSelectedIndex( ) Checkbox Checkbox( ) Checkbox(String str) Checkbox(String str, boolean on) Checkbox(String str, boolean on, CheckboxGroup cbGroup) Checkbox(String str, CheckboxGroup cbGroup, boolean on) boolean getState( ) void setState(boolean on) String getLabel( ) void setLabel(String str) TextField TextField( ) TextField(int numChars) TextField(String str) TextField(String str, int numChars) String getText( ) void setText(String str) void setEditable(boolean canEdit) TextArea TextArea( ) TextArea(int numLines, int numChars) TextArea(String str) TextArea(String str, int numLines, int numChars) void append(String str) void insert(String str, int index)
  79. 79. AWT Components • All components are subclass of Component class • Components allow the user to interact with application. A layout manager arranges components within a container (Frame/Applet/Panel). Adding and Removing Controls • add(Component compObj)- add components to the conatainer. Once it is added, it will automatically be visible whenever its parent window is displayed. Here, compObj is an instance of the control that you want to add. • void remove(Component obj)- remove a control from a window
  80. 80. © A.V.C College of Engineering
  81. 81. CS2305 PROGRAMMING PARADIGMS Scrollbars Scrollbar( ) Scrollbar(int style) Scrollbar(int style, int initialValue, int thumbSize, int min, int max) int getMinimum( ) int getMaximum( ) void setValues(int initialValue, int thumbSize, int min, int max) Label • Labels are components that hold text. • Labels don’t react to user input. It is used to identify components. Constructors • Label(String str) - constructs a label with left-aligned text. • Label(String str, int how) - constructs a label with the alignment specified by how. Methods • void setText(String str)- set the text in the label • String getText( )- return the text of label Example: The following example creates three labels and adds them to a frame..The labels are organized in the frame by the flow layout manager. import java.awt.*; Demo ob=new Demo("Label Demo"); public class Demo extends Frame{ Label lb1 = new Label("One"); Label lb2 = new Label("Two"); Label lb3 = new Label("Three"); FlowLayout flow= new FlowLayout(); Demo(String s){ super(s); setSize(200,200); setLayout(flow); add(lb1);add(lb2);add(lb3); setVisible(true); } public static void main(String arg[]){
  82. 82. } } Output: © A.V.C College of Engineering
  83. 83. CS2305 PROGRAMMING PARADIGMS Button A push button is a component that contains a label and that generates an event when it is pressed. Push buttons are objects of type Button. Constructors • Button( )- creates an empty button • Button(String str)- creates a button that contains str as a label. Methods • void setLabel(String str) -set the label in the button • String getLabel( ) -return the label of button Example: The following example creates three buttons and adds them to a frame. The buttons are organized in the frame by the flow layout manager. public static void main(String arg[]){ import java.awt.*; Demo ob=new Demo("Button Demo"); public class Demo extends Frame{ FlowLayout flow= new FlowLayout(); }} Output: Button b=new Button(); Button b1=new Button(); Button b2=new Button("Button 2"); Demo(String s){ super(s);setSize(200,200); setLayout(flow); b1.setLabel("Button 1"); add(b);add(b1);add(b2); setVisible(true); } List The List class provides a compact, multiple-choice, scrolling selection list. List object can be constructed to display any number of choices in the visible window. It allows the user to select multiple items. Constructors • List( )- allows to select one item at any one time • List(int numRows)- the value of numRows specifies the number of entries in the list that
  84. 84. © A.V.C College of Engineering
  85. 85. CS2305 PROGRAMMING PARADIGMS will be visible always • List(int numRows, boolean multipleSelect)- if multipleSelect is true, then the user may select two or more items at a time Method • void add(String name)- Here, name is the name of the item added to the list. The first form adds items to the end of the list. • void add(String name, int index) -adds the item at the index specified by index • String getSelectedItem( )- return the selected item • String[ ] getSelectedItems( )- return the selected items. Example: The following example creates a list and adds it to a frame. import java.awt.*; public class Demo extends Frame{ FlowLayout flow= new FlowLayout(); List l1=new List(2); List l2=new List(3); List l3=new List(4,true); Label lb1 = new Label("Dept"); Label lb2 = new Label("Dept"); Label lb3 = new Label("Dept"); Demo(String s){ super(s); setSize(200,300); setLayout(flow); l1.add("CSE");l1.add("ECE");l1.add("EEE");l1.add("MECH"); l2.add("CSE");l2.add("ECE");l2.add("EEE");l2.add("MECH"); l3.add("CSE");l3.add("ECE");l3.add("EEE");l3.add("MECH"); add(lb1);add(l1);add(lb2);add(l2);add(lb3);add(l3); setVisible(true); } public static void main(String arg[]){ Demo ob=new Demo("List Demo"); } }
  86. 86. © A.V.C College of Engineering
  87. 87. CS2305 PROGRAMMING PARADIGMS CheckBox A check box is a control that is used to turn an option on or off. It consists of a small box that can either contain a check mark or not. There is a label associated with each check box that describes what option the box represents. Constructors • Checkbox( )- check box whose label is initially blank • Checkbox(String str)- check box whose label is specified by str. • Checkbox(String str, boolean on) - allows you to set the initial state of the check box. If on is true, the check box is initially checked • Checkbox(String str, boolean on, CheckboxGroup cbGroup)- group is specified by cbGroup • Checkbox(String str, CheckboxGroup cbGroup, boolean on) Methods • boolean getState( ) • void setState(boolean on) • String getLabel( ) • void setLabel(String str) CheckboxGroup Create a set of mutually exclusive check boxes in which one and only one check box in the group can be checked at any one time. These check boxes are often called radio buttons. The default constructor is defined, which creates an empty group. Example: The following example creates a checkbox group (Gender) and checkboxes (Languages Known). import java.awt.*; public class Demo extends Frame{ FlowLayout flow= new FlowLayout(); Label l1=new Label("Gender"); Label l2=new Label("Languages Known"); CheckboxGroup cg=new CheckboxGroup(); Checkbox c1=new Checkbox("Male",cg,true); Checkbox c2=new Checkbox("Female",cg,false);
  88. 88. © A.V.C College of Engineering
  89. 89. Checkbox c3=new Checkbox("VisualBasic"); Checkbox c4=new Checkbox("C++"); Checkbox c5=new Checkbox("Java"); Checkbox c6=new Checkbox("C"); CS2305 PROGRAMMING PARADIGMS } } Output: Demo(String s){ super(s); setSize(200,200); setLayout(flow); add(l1);add(c1);add(c2); add(l2);add(c3);add(c4);add(c5);add(c6); setVisible(true); } public static void main(String arg[]){ Demo ob=new Demo("Checkbox Demo"); Choice The Choice class is used to create a pop-up list of items from which the user may choose. It allows the user to select single item at any time. Choice only defines the default constructor, which creates an empty list. To add a item to the list, call add( ). It has this general form: • void add(String name) • To determine which item is currently selected, you may call either getSelectedItem( ) or getSelectedIndex( ). import java.awt.*; public class Demo extends Frame{ FlowLayout flow= new FlowLayout(); Label lb=new Label("City"); Choice c=new Choice(); Demo(String s){ super(s); setSize(200,200);setLayout(flow); c.add("Chennai");c.add("Coimbatore"); c.add("KanyaKumari");c.add("Madurai"); c.add("Tirunelveli"); add(lb);add(c); setVisible(true); } public static void main(String arg[]){ Demo ob=new Demo("Checkbox Demo"); } }
  90. 90. © A.V.C College of Engineering
  91. 91. CS2305 PROGRAMMING PARADIGMS TextField Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse selections. • TextField( )- creates a default text field • TextField(int numChars)- creates a text field that is numChars characters wide • TextField(String str)- initializes the text field with the string contained in str • TextField(String str, int numChars) Methods • String getText( ) • void setText(String str) TextArea Simple multiline editor allow the user to enter strings. TextArea and TextField are subclass of TextComponent. Therefore, it supports the getText( ), setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described in TextField class. import java.awt.*; public class Demo extends Frame{ FlowLayout flow= new FlowLayout(); Label lb1=new Label("Name"); Label lb2=new Label("No"); Label lb3=new Label("Message"); TextField t1=new TextField(20); TextField t2=new TextField(15);
  92. 92. TextArea ta=new TextArea(2,10); Demo(String s){ super(s); setSize(250,200); setLayout(flow); add(lb1);add(t1); add(lb2);add(t2); add(lb3);add(ta); © A.V.C College of Engineering
  93. 93. CS2305 PROGRAMMING PARADIGMS setVisible(true); } public static void main(String arg[]){ Demo ob=new Demo("TextComponents Demo"); } } output:
  94. 94. © A.V.C College of Engineering