Upcoming SlideShare
Loading in...5







Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    Mcs024 Mcs024 Document Transcript

    • 1)AAnsObject-oriented programming (OOP) is a programming paradigm that represents concepts as"objects" that have data fields (attributes that describe the object) and associated proceduresknown as methods. Objects, which are usually instances of classes, are used to interact withone another to design applications and computer programsAn object-oriented program may be viewed as a collection of interacting objects, asopposed to the conventional model, in which a program is seen as a list of tasks(subroutines) to perform. In OOP, each object is capable of receiving messages,processing data, and sending messages to other objects. Each object can be viewed asan independent "machine" with a distinct role or responsibility. Actions (or "methods") onthese objects are closely associated with the object. For example, OOP datastructures tend to "carry their own operators around with them" (or at least "inherit" themfrom a similar object or class)—except when they must be serialized.Simple, non-OOP programs may be one "long" list(or commands). More complexprograms often group smaller sections of these statementsintofunctions or subroutines—each of which might perform a particular task. Withdesigns of this sort, it is common for some of the programs data to be global, i.e.,accessible from any part of the program. As programs grow in size, allowing anyfunction to modify any piece of data means that bugs can have wide-reaching effects.In contrast, the object-oriented approach encourages the programmer to place datawhere it is not directly accessible by the rest of the program. Instead, the data isaccessed by calling specially written functions, commonly called methods, which arebundled in with the data. These act as the intermediaries for retrieving or modifying thedata they control. The programming construct that combines data with a set of methodsfor accessing and managing those data is called an object. The practice of usingsubroutines to examine or modify certain kinds of data was also used in non-OOPmodular programming, well before the widespread use of object-orientedprogramming.An object-oriented program usually contains different types of objects, eachcorresponding to a particular kind of complex data to manage, or perhaps to a real-world object or concept such as a bank account, a hockey player, or a bulldozer. Aprogram might contain multiple copies of each type of object, one for each of the real-
    • world objects the program deals with. For instance, there could be one bank accountobject for each real-world account at a particular bank. Each copy of the bank accountobject would be alike in the methods it offers for manipulating or reading its data, but thedata inside each object would differ reflecting the different history of each account.Objects can be thought of as wrapping their data within a set of functions designed toensure that the data are used appropriately, and to assist in that use. The objectsmethods typically include checks and safeguards specific to the data types the objectcontains. An object can also offer simple-to-use, standardized methods for performingparticular operations on its data, while concealing the specifics of how those tasks areaccomplished. In this way alterations can be made to the internal structure or methodsof an object without requiring that the rest of the program be modified. This approachcan also be used to offer standardized methods across different types of objects. As anexample, several different types of objects might offer print methods. Each type ofobject might implement that print method in a different way, reflecting the different kindsof data each contains, but all the different print methods might be called in the samestandardized manner from elsewhere in the program. These features become especiallyuseful when more than one programmer is contributing code to a project or when thegoal is to reuse code between projects.Object-oriented programming has roots that can be traced to the 1960s. As hardwareand software became increasingly complex, manageability often became a concern.Researchers studied ways to maintain software quality and developed object-orientedprogramming in part to address common problems by strongly emphasizing discrete,reusable units of programming logic[citation needed]. The technology focuses on data ratherthan processes, with programs composed of self-sufficient modules ("classes"), eachinstance of which ("objects") contains all the information needed to manipulate its owndata structure ("members"). This is in contrast to the existing modular programming thathad been dominant for many years that focused on the function of a module, rather thanspecifically the data, but equally provided for code reuse, and self-sufficient reusableunits of programming logic, enabling collaboration through the use of linked modules(subroutines).As to the advantages of object-orientation over non-object-oriented software:
    • component-specific behavior - making details on how to handle a particular component the responsibility of the smaller component-specific machine ensures any time that component is handled, its machine will do so appropriately; polymorphic expressions - because component-specific machines performs operations tailored to its particular component, the same message sent to different machines can act differently; type abstraction - it often makes sense for several different types of components to use the same vocabulary for the operations their machines do; separation of concerns - leaving component-specific details to their machines means the process machine only needs to handle the more general, larger concerns of its process and the data required to manage it; plus, its less likely to be affected by changes in other components; adaptability - components that focus on their area of speciality can be adapted to unforeseen use simply by changing the components it uses, or making it available to another process machine; code reuse - components with a narrow focus and greater adaptability can leverage their development cost by being put to use more often.b)"Poly" means "many" and "morph" means "form". Polymorphism is theability of an object (or reference) to assume (be replaced by) or becomemany different forms of object.Example: function overloading, function overriding, virtual functions.Another example can be a plus ‗+‘ sign, used for adding two integers or forusing it to concatenate two strings.Subtype polymorphism, often referred to as simply polymorphism in the context of object-orientedprogramming, is the ability to create a variable, a function, or an object that has more than one form. In
    • principle, polymorphism can arise in other computing contexts and shares important similarities with theconcept of degeneracy in biology.The purpose of polymorphism is to implement a style of programming called message-passing in the [citation needed]literature , in which objects of various types define a common interface of operations for users.In strongly typed languages, polymorphism usually means that type A somehow derives from type B, ortype C implements an interface that represents type B. In weakly typed languages types are implicitlypolymorphic.Operator overloading of the numeric operators (+, -, *, and /) allows polymorphic treatment of the variousnumerical types: integer, unsigned integer, float, decimal, etc.; each of which have different ranges, bitpatterns, and representations. Another common example is the use of the "+" operator which allowssimilar or polymorphic treatment of numbers (addition), strings (concatenation), and lists (attachment).This is a lesser used feature of polymorphism.The primary usage of polymorphism in industry (object-oriented programming theory) is the abilityof objects belonging to different types to respond tomethod, field, or property calls of the same name,each one according to an appropriate type-specific behavior. The caller (calling code) likewise itsprogrammer, does not have to know the exact type of the callee (called object), thus the exact behavior isdetermined at run-time (this is called late binding or dynamic binding).The different objects involved only need to present a compatible interface to the clients (calling routines).That is, there must be public or internal methods, fields, events, and properties with the same name andthe same parameter sets in all the superclasses, subclasses and interfaces. In principle, the object typesmay be unrelated, but since they share a common interface, they are often implemented as subclasses ofthe same superclass. Though it is not required, it is understood that the different methods will alsoproduce similar results (for example, returning values of the same type).Polymorphism (which is strictly referring to subtype polymorphism in the context of this article) is not the [1]same as method overloading or method overriding, (which is known instead as ad-hoc [2]polymorphism ). Polymorphism is only concerned with the application of specific implementations toan interface or a more generic base class. Method overloading refers to methods that have the samename but different signatures inside the same class. Method overriding is where a subclass replaces theimplementation of one or more of its parents methods. Neither method overloading nor method overriding [3]is by itself an implementation of polymorphism.2)AA Platform-Independent Model (PIM) in software engineering is a model of a softwaresystem or business system, that is independent of the specific technological platformused to implement it.
    • The term platform-independent model is most frequently used in the context ofthe model-driven architecture approach.Platform independent is program running ondifferent processors like intel, AMD, Sun Micro Systems etc.; This model-drivenarchitecture approach corresponds the Object Management Group vision of ModelDriven Engineering.The main idea is that it should be possible to use a Model Transformation Language totransform a Platform-independent model into a Platform-specific model. In order toachieve this transformation, one can use a language compliant to the newlydefined QVT standard. Examples of such languages are VIATRA or ATLASTransformation Language. It means execution of the program is not restricted by thetype of o/s used.Java solves the problem of platform-independence by usingbyte code. The Java compiler does not produce nativeexecutable code for a particular machine like a C compilerwould. Instead it produces a special format called bytecode. Java byte code written in hexadecimal, byte by byte,looks like this:CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00 20 08This looks a lot like machine language, but unlike machinelanguage Java byte code is exactly the same on everyplatform. This byte code fragment means the same thing on aSolaris workstation as it does on a Macintosh PowerBook.Java programs that have been compiled into byte code stillneed an interpreter to execute them on any given platform.The interpreter reads the byte code and translates it intothe native language of the host machine on the fly. The mostcommon such interpreter is Suns program java (with a littlej). Since the byte code is completely platform independent,only the interpreter and a few native libraries need to beported to get Java to run on a new computer or operatingsystem. The rest of the runtime environment including the
    • compiler and most of the class libraries are written in Java.All these pieces, the javac compiler, the java interpreter,the Java programming language, and more are collectivelyreferred to as Java.b)*Write a program to find Fibonacci series of a given no. Example : Input - 8 Output - 1 1 2 3 5 8 13 21 */class Fibonacci{ public static void main(String args[]){ int num = Integer.parseInt(args[0]); //taking no. as commandline argument. System.out.println("*****Fibonacci Series*****"); int f1, f2=0, f3=1; for(int i=1;i<=num;i++){ System.out.print(" "+f3+" "); f1 = f2; f2 = f3; f3 = f1 + f2; } }}c)see .htm filed)Classpath is a parameter—set either on the command-line, or through an environmentvariable—that tells the Java Virtual Machine or the Java compiler where to look for user-defined classes andpackages.Suppose we have a package called org.mypackage containing the classes: HelloWorld (main class) SupportClass UtilClassand the files defining this package are stored physically under the directory D:myprogram (on Windows)or /home/user/myprogram (on Linux).The file structure will look like this:
    • Microsoft Windows LinuxD:myprogram /home/user/myprogram/ | | ---> org ---> org/ | | ---> mypackage ---> mypackage/ | | ---> --->HelloWorld.class HelloWorld.class ---> --->SupportClass.class SupportClass.class ---> --->UtilClass.class UtilClass.classWhen we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld.However we must also tell Java where to look for the files and directories defining our package. So tolaunch the program, we use the following command: Microsoft Windows Linux java -classpath D:myprogram java -classpath /home/user/myprogramorg.mypackage.HelloWorld org.mypackage.HelloWorldwhere: -classpath D:myprogram sets the path to the packages used in the program (on Linux, -classpath /home/user/myprogram) org.mypackage.HelloWorld is the name of the main classNote that if we ran Java in D:myprogram (on Linux, /home/user/myprogram/) then we would not need tospecify the classpath since Java implicitly looks in the current working directory for files containingclasses.[edit]Adding all JAR files in a directoryIn Java 6 and higher, one can add all jar-files in a specific directory to the classpath using wildcardnotation.Windows example:
    • java -classpath ".;c:mylib*" MyAppLinux example:java -classpath .:/mylib/* MyApp[edit]Setting the path through an environment variableThe environment variable named CLASSPATH may be alternatively used to set the classpath. For theabove example, we could also use on Windows:Sometimes you have to check the JAVA_HOME also, if it is pointing towards the right JDK versionset CLASSPATH=D:myprogramjava org.mypackage.HelloWorld[edit]Setting the path of a Jar fileNow, suppose the program uses a supporting library enclosed in a Jar file called supportLib.jar, physicallyin the directory D:myprogramlib.The corresponding physical file structure is :D:myprogram | ---> lib | ---> supportLib.jar | ---> org | --> mypackage | ---> HelloWorld.class ---> SupportClass.class ---> UtilClass.classWe should use the following command-line option:java -classpath D:myprogram;D:myprogramlibsupportLib.jarorg.mypackage.HelloWorldor alternatively:
    • set CLASSPATH=D:myprogram;D:myprogramlibsupportLib.jarjava org.mypackage.HelloWorld[edit]Setting the path in a Manifest fileSuppose that our program has been enclosed in a Jar file called helloWorld.jar, put directly inthe D:myprogram directory. We have the following file structure:D:myprogram | ---> helloWorld.jar | ---> lib | ---> supportLib.jarThe manifest file defined in this Jar file has this definition:Main-Class: org.mypackage.HelloWorldClass-Path: lib/supportLib.jarNote: Its important that the manifest file ends with either a new line or carriage return.Also, note that the classpath string in this case describes the location of the supportLib.jar file relative tothe location of the helloWorld.jar file, and not as an absolute file path (as it might be when setting the -classpath parameter on the command line, for example). Thus, the actual locations of the jar file and itssupport library are irrelevant so long as the relative directory structure between the two is preserved.To launch the program, we can use the following command:java -jar D:myprogramhelloWorld.jarIt is not necessary to define the Classpath to the program classes, or the support library classes, becauseit is already defined in the manifest file.Caution, it is useless to define the Main class at launch, the manifest of the JAR file must contain a line ofthe formMain-Class: classnamein order for the -jar option to work JavaDoc.
    • The syntax for specifying multiple library JAR files in the manifest file is to separate the entries with aspace:Class-Path: lib/supportLib.jar lib/supportLib2.jar3Axceptions are the customary way in Java to indicate to a calling method that an abnormalcondition has occurred. This article is a companion piece to this months DesignTechniques installment, which discusses how to use exceptions appropriately in yourprograms and designs. Look to this companion article for a tutorial on the nuts and bolts of whatexceptions are and how they work in the Java language and virtual machine.When a method encounters an abnormal condition (an exception condition) thatit cant handle itself, it may throw an exception. Throwing an exception is likethrowing a beeping, flashing red ball to indicate there is a problem that cant behandled where it occurred. Somewhere, you hope, this ball will be caught and theproblem will be dealt with. Exceptions are caught by handlers positioned alongthe threads method invocation stack. If the calling method isnt prepared to catchthe exception, it throws the exception up to itscalling method, and so on. If one ofthe threads of your program throws an exception that isnt caught by any methodalong the method invocation stack, that thread will expire. When you program inJava, you must position catchers (the exception handlers) strategically, so yourprogram will catch and handle all exceptions from which you want your programto recover.Exception classesIn Java, exceptions are objects. When you throw an exception, you throw anobject. You cant throw just any object as an exception, however -- only thoseobjects whose classes descend fromThrowable. Throwable serves as the base
    • class for an entire family of classes, declared in java.lang, that your program caninstantiate and throw. A small part of this family is shown in Figure 1.As you can see in Figure 1, Throwable has two directsubclasses,Exception and Error. Exceptions (members of the Exception family)are thrown to signal abnormal conditions that can often be handled by somecatcher, though its possible they may not be caught and therefore could result ina dead thread. Errors (members of theError family) are usually thrown for moreserious problems, such asOutOfMemoryError, that may not be so easy to handle. Ingeneral, code you write should throw only exceptions, not errors. Errors areusually thrown by the methods of the Java API, or by the Java virtual machineitself.The Exception class does not define any methods of its own. It inheritsmethods provided by Throwable.All exceptions have the methods defined by Throwable available to them.They are shown in the following list.Throwable fillInStackTrace( ) Returns a Throwable object that contains a completed stack trace.Throwable getCause( ) Returns the exception that underlies the current exception.String getLocalizedMessage( ) Returns a localized description.String getMessage( ) Returns a description of the exception.StackTraceElement[ ] getStackTrace( ) Returns an array that contains the stack trace.Throwable initCause(Throwable causeExc) Associates causeExc with the invoking exception as a cause of the invoking exception.void printStackTrace( ) Displays the stack trace.void printStackTrace(PrintStream stream) Sends the stack trace to the stream.void printStackTrace(PrintWriter stream) Sends the stack trace to the stream.void setStackTrace(StackTraceElement elements[ ]) Sets the stack trace to the elements passed in elements.String toString( ) Returns a String object containing a description of the exception.
    • The following program creates a custom exception type.class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; }}public class Main { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")"); if (a > 10) throw new MyException(a); System.out.println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } }}BAbstract classes in Java are classes which cannot be instantiated, meaningyou cannot create new instances of an abstract class. The purpose of anabstract class is to function as a base for subclasses. This text gets into thepurpose of abstract classes in more detail towards the end of this text.Here is a list of the topics covered in this text:
    • Declaring an Abstract ClassYou declare that a class is abstract by adding the abstract keyword to theclass declaration. Here is an example:public abstract class MyAbstractClass {}That is all there is to it. Now you cannot create instancesof MyAbstractClass. Thus, the following Java code is no longer valid:MyAbstractClass myClassInstance = new MyAbstractClass(); //not validIf you try to compile the code above, the Java compiler will generate an error.Abstract MethodsAn abstract class can have abstract methods. You declare a method abstractby adding the abstract keyword in front of the method declaration. Here ishow that looks:public abstract class MyAbstractClass {
    • public abstract void abstractMethod();}An abstract method has no implementation. It just has a method signature.If a class has an abstract method, the whole class must be declared abstract.Not all methods have to be abstract, even if the class is abstract. An abstractclass can have a mixture of abstract and non-abstract classes.Subclasses of an abstract class must implement (override) all abstractmethods of its abstract superclass. The non-abstract methods of thesuperclass are just inherited as they are. They can also be overridden, ifneeded.Here is an example subclass of MyAbstractClass:public class MySubClass extends MyAbstractClass { public void abstractMethod() { System.out.println("My method implementation"); }}Notice how MySubClass has to implement the abstractmethod abstractMethod() from its superclass MyAbstractClass.
    • The only time a subclass of an abstract class is not forced to implement allabstract methods of its superclass, is if the subclass is also an abstract class.The Purpose of Abstract ClassesThe purpose of abstract classes is to function as base classes which can beextended by subclasses to create a full implementation. For instance, imaginethat a certain process requires 3 steps: 1. The step before the action. 2. The action. 3. The step after the action.If the steps before and after the action are always the same, the 3-stepprocess could be implemented in an abstract superclass like this:public abstract MyAbstractProcess { public void process() { stepBefore(); action(); stepAfter(); }
    • public void stepBefore() { //implementation directly in abstract superclass } public abstract void action(); // implemented by subclasses public void stepAfter() { //implementation directly in abstract superclass }}Notice how the action() method is abstract. Subclassesof MyAbstractProcess can now extend MyAbstractProcess and justoverride the action() method.When the process() method of the subclass is called, the full process isexecuted, including the action() method of the subclass.Of course, the MyAbstractProcess did not have to be an abstract class tofunction as a base class. Nor did the action() method have to be abstracteither. You could have just used an ordinary class. However, by making themethod to implement abstract, and thus the class too, you signal clearly to theprogrammer, that this class should not be used as it is, but be used as a baseclass for a subclass, and that the abstract method should be implemented inthe subclass.
    • The above example did not have a default implementation forthe action() method. In some cases your superclass might actually have adefault implementation for the method that subclasses are supposed tooverride. In that case, you cannot make the method abstract. You can stillmake the superclass abstract though, even if it contains no abstract methods.Here is a more concrete example that opens a URL, processes it and closesthe connection to the URL afterwards.public abstract class URLProcessorBase { public void process(URL url) throws IOException { URLConnection urlConnection = url.openConnection(); InputStream input = urlConnection.getInputStream(); try{ processURLData(input); } finally { input.close(); } }
    • protected abstract void processURLData(InputStream input) throws IOException;}Notice how the processURLData() method is abstract. Subclassesof URLProcessorBasehas to implement this method.Subclasses of URLProcessorBase can process data downloaded fromURLs without worrying about opening and closing the network connection tothe URL. This is done by the URLProcessorBase. Subclasses only need toworry about processing the data from the InputStream passed tothe processURLData() metod. This makes it easier to implement classesthat processes data from URLs.Here is an example subclass:public class URLProcessorImpl extends URLProcessorBase { @Override protected void processURLData(InputStream input) throwsIOException { int data =;
    • while(data != -1){ System.out.println((char) data); data =; } }}Notice how the subclass only implements the processURLData() method,and nothing more. The rest of the code is inherited fromthe URLProcessorBase superclass.Here is an example of how to use the URLProcessorImpl class:URLProcessorImpl urlProcessor = new URLProcessorImpl();urlProcessor.process(new URL(""));The process() method is called, which is implemented inthe URLProcessorBasesuperclass. This method in turn callsthe processURLData() in the URLProcessorImplclass.Abstract classes improve the situation by preventing a developer frominstantiating the base class, because a developer has marked it as havingmissing functionality. It also provides compile-time safety so that you canensure that any classes that extend your abstract class provide the bare
    • minimum functionality to work, and you dont need to worry about putting stubmethods (like the one above) that inheritors somehow have to magically knowthat they have to override a method in order to make it work.Interfaces are a totally separate topic. An interface lets you describe whatoperations can be performed on an object. You would typically use interfaceswhen writing methods, components, etc. that use the services of othercomponents, objects, but you dont care what the actual type of object you aregetting the services from is.Consider the following method:public void saveToDatabase(IProductDatabase database) { database.addProduct(this.getName(), this.getPrice());}You dont care about whether the database object inherits from any particularobject, you just care that it has an addProduct method. So in this case, aninterface is better suited than making all of your classes happen to inherit fromthe same base class.Sometimes the combination of the two works very nicely. For example:abstract class RemoteDatabase implements IProductDatabase { public abstract String[] connect(); public abstract void writeRow(string col1, string col2); public void addProduct(String name, Double price) { connect(); writeRow(name, price.toString()); }}class SqlDatabase extends RemoteDatabase { //TODO override connect and writeRow}class OracleDatabase extends RemoteDatabase { //TODO override connect and writeRow}class FileDatabase implements IProductDatabase { public void addProduct(String name, Double price) {
    • //TODO: just write to file }}Multilevel inheritance is a java feature where the properties of a class areinherited by a class which extends one or more classes which extend itsfeatures...Example:public class A {public String getName(){return "Vijay";}}public class B extends A {public int getAge() {return 24;}}public class C extends B {public String getAddress(){return "Utter Pradesh,INDIA";}}public class D extends C {public void print {System.out.println(getName());System.out.println(getAge());System.out.println(getAddress());}}This method would print the following in the console:
    • Vijay24Pradesh,INDIAHere in class D you are calling methods that are available inside classes A, B &C. Though D extends only class C, it would in turn inherit the properties of theclasses extended by C and its parents.This is multi level inheritance.4aThe final keyword is used to create constants, i.e. data which is always for reading and neverneeds to change, once initialized. A simple example would be MaxAge, in a software to managedetails of employees in a company. Lets say the maximum age of retirement is 60, so we knowthat no employee can have age greater than 60. So I will write –final int MaxAge = 60;Now anywhere in other part of software I can use the value simply for validation as follows:If (age > MaxAge) // age is already declared somewhere as intSystem.out.println(―There is an error. Invalid Age.‖); // Oops error in age!The static keyword is used to create variables which are shared by all instances (objects) of theclass. The scope of usage of such a variable is class, i.e. it can be accessed only with the classunless it is declared public. Their lifetime is same as that of the program, which means theyalways exist and you dont need to create object to access them. A good example can be avariable to count the total number of errors in a class and its objects. The following is oneexample:static int TotalErrors = 0;Then we can write anywhere code like the following –If (age > MaxAge)
    • {System.out.println(―There is an error. Invalid Age!‖);TotalErrors++; // There was an error so increment it}Did that make any sense?Actually I am a C++ guy, so if it did not make any sense, just forgive me. I tried my best. =)@To XTremeHell [In response to his assertion that const and final are different]Sorry sir, you need to go back to read the textbooks again. Javas "final" and C++ "const" areindeed ABSOLUTELY same. The value of const need not be known at compile time. See theC++ code below:-int var = 0;DoSomethingWithVar(&var); // The function modifies var.const int myReadOnlyValue = var;The point is "myReadOnlyValue" is a constant. Now can you tell me XTremeHell, how thecompiler is supposed to know the value of myReadOnlyValue, even though it is a constant?BIn the normal cases a simple question is enough to find out if we needinheritance or aggregation. If The new class is more or less as the original class. Use inheritance. The new class is now a subclass of the original class. If the new class must have the original class. Use aggregation. The new class has now the original class as a member.However, there is a big gray area. So we need several other tricks. If we have used inheritance (or we plan to use it) but we only use part of the interface, or we are forced to override a lot of functionality to keep the correlation logical. Then we have a big nasty smell that indicates that we had to use aggregation. If we have used aggregation (or we plan to use it) but we find out we need to copy almost all of the functionality. Then we have a smell that points in the direction of inheritance.
    • To cut it short. We should use aggregation if part of the interface is not used orhas to be changed to avoid an illogical situation. We only need to useinheritance, if we need almost all of the functionality without major changes. Andwhen in doubt, use Aggregation.An other possibility for, the case that we have an class that needs part of thefunctionality of the original class, is to split the original class in a root class and asub class. And let the new class inherit from the root class. But you should takecare with this, not to create an illogical separation.Lets add an example. We have a class Dog with methods: Eat, Walk, Bark,Play.class Dog Eat; Walk; Bark; Play;end;We now need a class Cat, that needs Eat, Walk, Purr, and Play. So first tryto extend it from a Dog.class Cat is Dog Purr;end;Looks, alright, but wait. This cat can Bark (Cat lovers will kill me for that). And abarking cat violates the principles of the universe. So we need to override theBark method so that it does nothing.class Cat is Dog Purr; Bark = null;end;Ok, this works, but it smells bad. So lets try an aggregation:class Cat has Dog; Eat = Dog.Eat; Walk = Dog.Walk; Play = Dog.Play;
    • Purr;end;Ok, this is nice. This cat does not bark anymore, not even silent. But still it has aninternal dog that wants out. So lets try solution number three:class Pet Eat; Walk; Play;end;class Dog is Pet Bark;end;class Cat is Pet Purr;end;This is much cleaner. No internal dogs. And cats and dogs are at the same level.We can even introduce other pets to extend the model. Unless it is a fish, orsomething that does not walk. In that case we again need to refactor. But that issomething for an other time.CDifference Between Interface and Abstract Class23/04/2008 1. Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior. 2. Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. 3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
    • 4. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”. 5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. 6. A Java class can implement multiple interfaces but it can extend only one abstract class. 7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists. 8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.DJava provides the StringBuffer and String classes, and the String class is used tomanipulate character strings that cannot be changed. Simply stated, objects of type String areread only and immutable. The StringBuffer class is used to represent characters that can bemodified.The significant performance difference between these two classes isthat StringBuffer is faster than String when performing simpleconcatenations. In String manipulation code, character strings are routinelyconcatenated. Using the String class, concatenations are typically performed asfollows: String str = new String ("Stanford "); str += "Lost!!";If you were to use StringBuffer to perform the same concatenation, you wouldneed code that looks like this: StringBuffer str = new StringBuffer ("Stanford "); str.append("Lost!!");
    • Developers usually assume that the first example above is more efficientbecause they think that the second example, which uses theappend method forconcatenation, is more costly than the first example, which uses the + operator toconcatenate two Stringobjects.The + operator appears innocent, but the code generated produces somesurprises. Using a StringBuffer for concatenation can in fact produce code thatis significantly faster than using a String. To discover why this is the case, wemust examine the generated bytecode from our two examples. The bytecode forthe example using String looks like this:0 new #7 <Class java.lang.String>3 dup4 ldc #2 <String "Stanford ">6 invokespecial #12 <Method java.lang.String(java.lang.String)>9 astore_110 new #8 <Class java.lang.StringBuffer>13 dup14 aload_115 invokestatic #23 <Method java.lang.String valueOf(java.lang.Object)>18 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>21 ldc #1 <String "Lost!!">23 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>26 invokevirtual #22 <Method java.lang.String toString()>29 astore_1The bytecode at locations 0 through 9 is executed for the first line of code,namely: String str = new String("Stanford ");Then, the bytecode at location 10 through 29 is executed for the concatenation:
    • str += "Lost!!";Things get interesting here. The bytecode generated for the concatenationcreates a StringBuffer object, then invokes itsappend method: thetemporary StringBuffer object is created at location 10, and its append methodis called at location 23. Because the String class is immutable,a StringBuffer must be used for concatenation.After the concatenation is performed on the StringBuffer object, it must beconverted back into a String. This is done with the call to the toString methodat location 26. This method creates a new String object from thetemporary StringBufferobject. The creation of thistemporary StringBuffer object and its subsequent conversion back intoa String object are very expensive.In summary, the two lines of code above result in the creation of three objects:1. A String object at location 02. A StringBuffer object at location 103. A String object at location 26Now, lets look at the bytecode generated for the example using StringBuffer:0 new #8 <Class java.lang.StringBuffer>3 dup4 ldc #2 <String "Stanford ">6 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>9 astore_110 aload_111 ldc #1 <String "Lost!!">13 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>16 pop
    • The bytecode at locations 0 to 9 is executed for the first line of code: StringBuffer str = new StringBuffer("Stanford ");The bytecode at location 10 to 16 is then executed for the concatenation: str.append("Lost!!");Notice that, as is the case in the first example, this code invokesthe append method of a StringBuffer object. Unlike the first example, however,there is no need to create a temporary StringBuffer and then convert it intoa String object. This code creates only one object, the StringBuffer, atlocation 0.In conclusion, StringBuffer concatenation is significantly fasterthan String concatenation. Obviously, StringBuffers should be used in thistype of operation when possible. If the functionality of the String class isdesired, consider using aStringBuffer for concatenation and then performingone conversion to String.5AFile Handling in JavaFor file handling in java, the package known as is available. This packagecontains all the required classes needed to perform input and output (I/O) in Java.Streams
    • The sequence of data can be defined as a stream. Java defines two types of streamswhich are given below :1. Byte2. CharactersByte StreamFor dealing input and output of bytes, byte stream is employed. For reading and writingbinary data it is incorporated. Binary Stream uses two abstract classes for input andoutput. These are InputStream class and OutputStream class respectively. To read datafrom the source InputStream is used and to write data to a destination OutputStream isused.The class hierarchy of the Byte Stream is given below :The byte stream classes are given below :
    • Byte Stream Classes Detail The InputStream is an abstract super class .All theInputStream classes representing an input stream of bytes is the subclass of this super class. The OutputStream is an abstract super class .All theOutputStream classes representing an output stream of bytes is the subclass of this super class.FileInputStream In a file system, it gets input bytes from a file.FileOutputStream Using it you can write data to a File or to a FileDescriptor. A ByteArrayInputStream has an internal buffer. This bufferByteArrayInputStream can retain bytes read from the stream Data can be written into a byte array using the outputByteArrayOutputStream stream of ByteArrayOutputStream. The input streams can be logically concatenated usingSequenceInputStream SequenceInputStream. The strings content supplies bytes read to an input stream which is created by an application.StringBufferInputStream The StringBufferInputStream class allows an application to do this. It has some additional input stream used as basic dataFilterInputStream source, These input streams can provide transformation of data and extra functionality.
    • All the classes that filter output streams is the subclassesFilterOutputStream of the FilterOutputStream superclass. It allows an application to read javas data type using anDataInputStream input stream which is independent of machine. It allows an application to write javas data type(primitive)DataOutputStream to an output stream. It provides additional functionality to the input stream suchBufferedInputStream as capability to buffer. It also supports reset and mark methods.BufferedOutputStream The buffered output stream is applied by this class. It provide ability to the other output stream to print severalPrintStream data values representation. The data byte written on piped output stream is providedPipedInputStream by PipedInputStream. But before that it must connect to the piped output stream. For creating communication pipe, piped output streamPipedOutputStream should be connected to piped output stream. To sum up the ability to "push back" or "unread" one bytePushbackInputStream to other input stream, a PushbackInputStream is used. For accessing a file randomly (for reading or writing) thisRandomAccessFile class is incorporated.
    • Methods defined by InputStreamAfter creating InputStream object, you can perform additional operations on the streamusing given below methods : Methods Descriptionpublic void The output stream of a file is closed using this function. Before thatclose() throws it releases any resource. This function throws IOException.IOException{}protected void This function clears the connection to the file. It throws anfinalize()throws IOException.IOException {}public int This function reads the data from the InputStream and return intread(int which is next byte of data. It also returnsr)throws -1 if end of file is reached.IOException{}public int This method reads data equal to length of r from the input streamread(byte[] r) using array. The total number of bytes read is returned afterthrows finishing reading. When end of file reached it returns -1.IOException{}public intavailable() This function returns the number of bytes available for reading fromthrows file input stream. The return type is int.IOException{}
    • Method defined by OutputStreamOnce you have OutputStream object in hand then there is a list of helper methods whichcan be used to write to stream or to do other operations on the stream. Methods Descriptionpublic void close() throws This function closes the output stream of the fileIOException{} and throws IOException.protected void finalize()throws This function closes the connection to the fileIOException{} and throws IOException.public void write(int w)throws Using this function, you can write specifiedIOException{} bytes to the output stream. This function is used to write bytes of lengthpublic void write(byte[] w) equal to w to the output stream from the the mentioned byte array.Character StreamFor handling the input and output of characters Character Stream is incorporated,which streamlines internationalization.The hierarchical distribution of Character stream is different from Byte Stream. Thehierarchical tree of Character Stream is topped by the Reader and Writer abstractclasses. Reader abstract class is used for input while Writer abstract class is used foroutput.The method defined by Reader abstract class is given below :
    • Function / Method Descriptionabstract void close( ) throws The input source is closed using this function.IOException This function set a mark in the input stream at thevoid mark(int numChars) throws current point. This Point will remain valid tillIOException numChars characters are read. If the stream support mark( )/reset( ) , thisboolean markSupported( ) function returns true. The input streams next available character isint read( ) throws IOException return by this function as an integer representation. This function reads the characters from bufferint read(char buffer[ ]) throws equal to the length of buffer.length and it returnsIOException the number of successful characters read.abstract int read(char buffer[ This function returns the count of the characters],int offset, int numChars) successfully read from buffer starting fromthrows IOException buffer[offset] up to numChars.boolean ready( ) throws If the input is pending, it returns true otherwiseIOException false. This function resets the input pointer to thevoid reset( ) throws IOException previously set mark.long skip(long numChars) This function skips the number of input characters
    • throws IOException equal to numChars. It returns the count of actually skipped characters.The method defined by Writer abstract class is given below :Function / Method Description This function adds ch at the end of theWriter append(char ch) throws output stream which invoked it. It alsoIOException returns reference to the stream. This function adds the chars to the end ofWriter append(CharSequence chars) the output stream which invoked it. It alsothrows IOException returns a reference to the stream. This function adds a sub range of chars toWriter append(CharSequence chars, the end of the output stream. It returns aint begin, int end) throws IOException reference to the stream.abstract void close( ) throws The output stream is closed by this function.IOExceptionabstract void flush( ) throws This function flushes the buffer of output.IOException This function writes the character to thevoid write(int ch) throws IOException output stream. The characters are in the low-order 16 bits of ch . Using this function you can write to thevoid write(char buffer[ ]) throws output stream -a complete array of
    • IOException characters . This function is used to writes a sub rangeabstract void write(char buffer[ ],int of numChars characters from the arrayoffset, int numChars) throws buffer to the output stream beginning atIOException buffer[offset].void write(String str) throws Using this function you can writes str to theIOException output stream. Using this function, from the string str ,youvoid write(String str, int offset, int can write a sub range of numCharsnumChars) characters.The File ClassIn spite of classes available to support file I/O, Java has a class named as File, whichcontains information about a file. For manipulating a file or the computers file system,this class is very effective and efficient. This class is used for creation of files anddirectories, file searching, file deletion etc.Once you have File object in hand then there is a list of helper methods which can beused manipulate the files, which are given below : Methods Descriptionpublic String This function returns the file or directorys name specified bygetName() the pathname. This function returns the parent directory pathname string.public String The pathname of the directory is passed to know its parent
    • getParent() pathname string. If the pathname doesnt have parent directory, it returns null.public File getParent This function returns the parent directory abstract pathnameFile() and it returns null if it doesnt have parent directory.public String To convert the abstract pathname into a pathname string, wegetPath() use this function.public boolean This function return true if this abstract pathname is absoluteisAbsolute() otherwise returns false.public String To find the absolute pathname string of the provided abstractgetAbsolutePath() pathname, we incorporate this method. This function is used to check if the application can read thepublic boolean file provided by this abstractcanRead() pathname. This function returns true if the file name provided by the abstract pathname exists otherwise return false. This function is used to check if the application can modify to the file provided through this abstractpublic boolean pathname. This function returns true if the file name providedcanWrite() by the abstract pathname exists and allowed to write, otherwise return false.public boolean This function returns true if the file name provided by theexists() abstract pathname exists otherwise return false.public boolean This function returns true if the file represented by the
    • isDirectory() abstract pathname is a directory otherwise returns false. This function is used to test whether the file represented bypublic boolean the abstract pathname exist and also checks whether it is aisFile() normal file. If it is , it will return true otherwise return false.public long This function is used to return the last modification time of thelastModified() file represented by the abstract pathname. This function finds the length of the file of the file representedpublic long length() by the abstract pathname and return it. It returns unspecified if the pathname represented is a directory.public boolean This function is used to create a new file which has the namecreateNewFile() provided by its abstract pathname. It will return true if the filethrows IOException created successfully otherwise returns false.public boolean This function is used to delete the file/directory representeddelete() by the abstract pathname.public void This function is used to delete the file represented by thedeleteOnExit() abstract pathname when the virtual machine terminates. This function returns an array of strings naming the files andpublic String[] list() directories in the directory specified by its abstract pathname.public String[] This function returns an array of strings naming the files andlist(FilenameFilter directories in the directory specified by its abstract pathnamefilter) that satisfy the specified filter.
    • public File[] This functions returns an array of abstract pathnameslistFiles() represented by the files in the directory. This function returns an array of abstract pathnamespublic File[] represented by the files and directorieslistFiles(FileFilter in the directory represented by this abstract pathname thatfilter) satisfy the specified filter. This function creates the directory named by this abstractpublic boolean pathname. this function returns true if the file createdmkdir() successfully otherwise false. This method creates the directory named by this abstract pathname, including anypublic boolean necessary but nonexistent parent directories. Returns true ifmkdirs() and only ifbr> the directory was created, along with all necessary parent directories; false otherwisepublic boolean This function renames the file represented by this abstractrenameTo(File pathname.dest)public boolean This function is used to set the last modification time of thesetLastModified(long file/ directory specified by the abstracttime) pathname.public boolean This function sets the file provided through abstractsetReadOnly() pathname to read-only mode. If it succeeded, it returns true
    • otherwise returns false.public String This function is used to return the pathname string of thetoString() abstract pathname provided.FileReader ClassFileReader class inherits from the InputStreamReader class. For reading streams ofcharacters, this class is used.Once you have FileReader object in hand then there is a list of helper methods whichcan be used manipulate the files :Method / DescriptionFunctionpublic intread() This function reads a single character at a time and returns the countthrows of number of character read.IOExceptionpublic intread(char [] This function is used to read characters. An array is used to readc, int offset, len)package com.mkyong.file;import;
    • import;import;import;public class AppendToFileExample{ public static void main( String[] args ) { try{ String data = " This content will append to the endof the file"; File file =new File("javaio-appendfile.txt"); //if file doesnt exists, then create it if(!file.exists()){ file.createNewFile(); } //true = append file
    • FileWriter fileWritter = newFileWriter(file.getName(),true); BufferedWriter bufferWritter = newBufferedWriter(fileWritter); bufferWritter.write(data); bufferWritter.close(); System.out.println("Done"); }catch(IOException e){ e.printStackTrace(); } }}b)A checked exception is any subclass of Exception (or Exception itself),excluding class RuntimeException and its subclasses.Making an exception checked forces client programmers to deal with thepossibility that the exception will be thrown. eg, IOException thrown read() methodUnchecked exceptions are RuntimeException and any of its subclasses. ClassError and its subclasses also are unchecked.With an unchecked exception, however, the compiler doesnt force clientprogrammers either to catch the exception or declare it in a throws clause.
    • In fact, client programmers may not even know that the exception could bethrown. eg, StringIndexOutOfBoundsException thrown by Strings charAt()method.Checked exceptions must be caught at compile time. Runtime exceptions donot need to be. Errors often cannot be, as they tend to be unrecoverable.public void storeDataFromUrl(String url){ try { String data = readDataFromUrl(url); } catch (BadUrlException e) { e.printStackTrace(); } } public String readDataFromUrl(String url) throws BadUrlException{ if(isUrlBad(url)){ throw new BadUrlException("Bad URL: " + url); }
    • String data = null; //read lots of data over HTTP and return //it as a String instance. return data; }As you can see the readDataFromUrl() method throws a BadUrlException. Ihave created BadUrlException myself. BadUrlException is a checkedexception because it extends java.lang.Exception: public class BadUrlException extends Exception { public BadUrlException(String s) { super(s); } }If storeDataFromUrl() wants to call readDataFromUrl() it has only two choices.Either it catches the BadUrlException or propagates it up the call stack. The
    • storeDataFromUrl() listed above catches the exception. ThisstoreDataFromUrl() implementation propagates the BadUrlException instead: public void storeDataFromUrl(String url) throws BadUrlException{ String data = readDataFromUrl(url); }Notice how the try catch block is gone and a "throws BadUrlException"declaration is added instead. Now, lets see how it looks with uncheckedexceptions. First I change the BadUrlException to extendjava.lang.RuntimeException instead: public class BadUrlException extends RuntimeException { public BadUrlException(String s) { super(s); } }Then I change the methods to use the now unchecked BadUrlException: public void storeDataFromUrl(String url){
    • String data = readDataFromUrl(url); } public String readDataFromUrl(String url) { if(isUrlBad(url)){ throw new BadUrlException("Bad URL: " + url); } String data = null; //read lots of data over HTTP and //return it as a String instance. return data; }Notice how the readDataFromUrl() method no longer declares that it throwsBadUrlException. The storeDataFromUrl() method doesnt have to catch theBadUrlException either. The storeDataFromUrl() method can still choose to
    • catch the exception but it no longer has to, and it no longer has to declare thatit propagates the exception.6Aava provides built-in support for multithreaded programming. A multithreaded program contains two or more partsthat can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path ofexecution.A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitaskingprocesses.I need to define another term related to threads: process: A process consists of the memory space allocated by theoperating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of aprocess. A process remains running until all of the non-daemon threads are done executing.Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle timecan be kept to a minimum.Life Cycle of a Thread:A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies.Following diagram shows complete life cycle of a thread.Above mentioned stages are explained here:New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. Itis also referred to as a born thread.
    • Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered tobe executing its task.Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform atask.A thread transitions back to the runnable state only when another thread signals the waiting thread to continueexecuting.Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in thisstate transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.Thread Priorities:Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). Bydefault, every thread is given priority NORM_PRIORITY (a constant of 5).Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very muchplatform dependentant.Creating a Thread:Java defines two ways in which this can be accomplished:You can implement the Runnable interface.You can extend the Thread class, itself.Create Thread by Implementing Runnable:The easiest way to create a thread is to create a class that implements the Runnable interface.To implement Runnable, a class need only implement a single method called run( ), which is declared like this:public void run( )You will define the code that constitutes the new thread inside run() method. It is important to understand that run()can call other methods, use other classes, and declare variables, just like the main thread can.After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class.Thread defines several constructors. The one that we will use is shown here:Thread(Runnable threadOb, String threadName);Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread isspecified by threadName.After the new thread is created, it will not start running until you call its start( ) method, which is declared withinThread. The start( ) method is shown here:void start( );here are two ways of creating a thread.1. Extending the Thread class
    • Ex: public class ThreadExample extends Thread {.....}2. Implementing the Runnable InterfaceEx: public class ThreadExample implements Runnable {...........}notify() is used to unblock one waiting thread; notifyAll() is used to unblockall of them. Using notify() is preferable (for efficiency) when only oneblocked thread can benefit from the change (for example, when freeing abuffer back into a pool). notifyAll() is necessary (for correctness) if multiplethreads should resume (for example, when releasing a "writer" lock on a filemight permit all "readers" to resume).b)Layout managers are software components used in widget toolkits which have theability to lay out widgets by their relative positions without using distance units. It is oftenmore natural to define component layouts in this manner than to define their positionin pixels or common distance units, so a number of popular widget toolkits include thisability by default. Widget toolkits that provide this function can generally be classifiedinto two groups: Those where the layout behavior is coded in special graphic containers. This is the case in XUL and the .NET Framework widget toolkit (both in Windows Forms and in XAML). Those where the layout behavior is coded in layout managers, that can be applied to any graphic container. This is the case in the Swing widget toolkit that is part of the Java API.
    • Explain different layout manager in Java.A layout manager organizes the objects in a containerDifferent layouts are used to organize or to arrange objects1. Border Layout:- It has five areas for holding components: north, east, west, south and center- When there are only 5 elements to be placed, border layout is the right choice2. Flow Layout:- Default layout manager.- It lays out the components from left to right3. Card Layout:- Different components at different times are laid out- Controlled by a combo box, determining which panel the Card layout displays4. Grid Layout:- A group of components are laid out I equal size and displays them in certain rows and columns5. Grid Bag Layout:- Flexible layout for placing components within a grid of cells- Allows certain components to span more than one cell- The rows of the grid are not of the same height and height7AA Java applet is an applet delivered to users in the form of Java bytecode. Java appletscan be part of a web page and executed by the Java Virtual Machine (JVM) ina process separate from the web browser, or run in Suns AppletViewer, a stand-alonetool for testing applets. Java applets were introduced in the first version of the Javalanguage in 1995, and are written in programming languages that compile to Java
    • bytecode, usually in Java, but also in other languages suchas Jython,[8] JRuby,[9] or Eiffel (via SmartEiffel).[10]Java applets run at very fast speeds comparable to, but generally slower than, othercompiled languages such as C++, but until approximately 2011 many times fasterthan JavaScript.[11] In addition they can use 3D hardware acceleration that is availablefrom Java. This makes applets well suited for non-trivial, computation intensivevisualizations. As browsers have gained support for hardware accelerated graphicsthanks to the canvas technology (or specifically WebGL in the case of 3D graphics), aswell as just in time compiled JavaScript, the speed difference has become lessnoticeable.Since Javas bytecode is cross-platform or platform independent, Java applets can beexecuted by browsers for many platforms, including Microsoft Windows, Unix, OSX and Linux. It is also trivial to run a Java applet as an application software with verylittle extra code so that it can be run directly from the integrated developmentenvironment (IDE).import java.applet.Applet;import java.awt.*;// Applet code for the "Hello, world!" example.// This should be saved in a file named as "".public class HelloWorld extends Applet { // This method is mandatory, but can be empty (i.e., have noactual code). public void init() { } // This method is mandatory, but can be empty.(i.e.,have noactual code). public void stop() { } // Print a message on the screen (x=20, y=10). public void paint(Graphics g) { g.drawString("Hello, world!", 20,10); // Draws a circle on the screen (x=40, y=30). g.drawArc(40,30,20,20,0,360); }}
    • mport java.applet.*;import java.awt.*;import java.awt.event.*;public class Mouse1 extends Applet implements MouseListener, MouseMotionListener { int width, height; int mx, my; // the mouse coordinates boolean isButtonPressed = false; public void init() { width = getSize().width; height = getSize().height; setBackground( ); mx = width/2; my = height/2; addMouseListener( this ); addMouseMotionListener( this ); } public void mouseEntered( MouseEvent e ) { // called when the pointer enters the applets rectangular area } public void mouseExited( MouseEvent e ) { // called when the pointer leaves the applets rectangular area } public void mouseClicked( MouseEvent e ) { // called after a press and release of a mouse button // with no motion in between // (If the user presses, drags, and then releases, there will be // no click event generated.) } public void mousePressed( MouseEvent e ) { // called after a button ispressed down isButtonPressed = true; setBackground( Color.gray ); repaint(); // "Consume" the event so it wont be processed in the // default manner by the source which generated it. e.consume(); } public void mouseReleased( MouseEvent e ) { // called after a button isreleased isButtonPressed = false; setBackground( ); repaint(); e.consume(); } public void mouseMoved( MouseEvent e ) { // called during motion when nobuttons are down mx = e.getX(); my = e.getY(); showStatus( "Mouse at (" + mx + "," + my + ")" ); repaint();
    • e.consume(); } public void mouseDragged( MouseEvent e ) { // called during motion withbuttons down mx = e.getX(); my = e.getY(); showStatus( "Mouse at (" + mx + "," + my + ")" ); repaint(); e.consume(); } public void paint( Graphics g ) { if ( isButtonPressed ) { g.setColor( ); } else { g.setColor( Color.gray ); } g.fillRect( mx-20, my-20, 40, 40 ); }}b)8JavaBeans are reusable software components for Java. Practically, they are classes written inthe Java programming language conforming to a particular convention. They are used toencapsulate many objects into a single object (the bean), so that they can be passed around as
    • a single bean object instead of as multiple individual objects. A JavaBean is a Java Object thatisserializable, has a 0-argument constructor, and allows access to properties using getter andsetter methods.A Java Bean is a software component that has been designed to be reusable in a variety of differentenvironments. There is no restriction on the capability of a Bean. It may perform a simple function, suchas checking the spelling of a document, or a complex function, such as forecasting the performance of astock portfolio. A Bean may be visible to an end user. One example of this is a button on a graphical userinterface. A Bean may also be invisible to a user. Software to decode a stream of multimedia informationin real time is an example of this type of building block. Finally, a Bean may be designed to workautonomously on a users workstation or to work in cooperation with a set of other distributedcomponents. Software to generate a pie chart from a set of data points is an example of a Bean that canexecute locally. However, a Bean that provides real-time price information from a stock or commoditiesexchange would need to work in cooperation with other distributed software to obtain its data. We will see shortly what specific changes a software developer must make to a class so that it is usable as a Java Bean. However, one of the goals of the Java designers was to make it easy to use this technology. Therefore, the code changes are minimal. Advantages of Java Beans A software component architecture provides standard mechanisms to deal with software building blocks. The following list enumerates some of the specific benefits that Java technology provides for a component developer: A Bean obtains all the benefits of Javas "write-once, run-anywhere" paradigm. The properties, events, and methods of a Bean that are exposed to an application builder tool can be controlled. A Bean may be designed to operate correctly in different locales, which makes it useful in global markets. Auxiliary software can be provided to help a person configure a Bean. This software is only needed when the design-time parameters for that component are being set. It does not need to be included in the run-time environment. The configuration settings of a Bean can be saved in persistent storage and restored at a later time. A Bean may register to receive events from other objects and can generate events that are sent to other objects.