Applet Structure and Elements

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 18

Applet Structure and Elements The Java API Applet class provides what you need to design the

appearance and manage the behavior of an applet. This class provides a graphical user interface (GUI component called a Panel and a number of methods. To create an applet! you e"tend (or subclass the Applet class and implement the appearance and behavior you want. The applet#s appearance is created by drawing onto the Panel or by attaching other GUI components such as push buttons! scrollbars! or te"t areas to the Panel. The applet#s behavior is defined by implementing the methods. Extending a Class $ost classes of any comple"ity e"tend other classes. To e"tend another class means to write a new class that can use the fields and methods defined in the class being e"tended. The class being e"tended is the parent class! and the class doing the e"tending is the child class. Another way to say this is the child class inherits the fields and methods of its parent or chain of parents. %hild classes either call or override inherited methods. This is called single inheritance. The SimpleApplet class e"tends Applet class! which e"tends the Panel class! which e"tends the Container class. The Container class e"tends Object! which is the parent of all Java API classes. The Applet class provides the init! start! stop! destroy! and paint methods you saw in the e"ample applet. The SimpleApplet class overrides these methods to do what the SimpleApplet class needs them to do. The Applet class provides no functionality for these methods. &owever! the Applet class does provide functionality for the setBackground method!which is called in the init method. The call to setBackground is an e"ample of calling a method inherited from a parent class in contrast to overriding a method inherited from a parent class. 'ou might wonder why the Java language provides methods without implementations. It is to provide conventions for everyone to use for consistency across Java APIs. If everyone wrote their own method to start an applet! for e"ample! but gave it a different name such as begin or go! the applet

code would not be interoperable with other programs and browsers! or portable across multiple platforms. (or e"ample! )etscape and Internet *"plorer +now how to loo+ for the init and start methods. Behavior An applet is controlled by the software that runs it. Usually! the underlying software is a browser! but it can also be appletviewer as you saw in the e"ample. The underlying software controls the applet by calling the methods the applet inherits from the Applet class. The init method is called when the applet is first created and loaded by the underlying software. This method performs one,time operations the applet needs for its operation such as creating the user interface or setting the font. In the e"ample! the init method initiali-es the te"t string and sets the bac+ground color.
The init Method:

The start method is called when the applet is visited such as when the end user goes to a web page with an applet on it. The e"ample prints a string to the console to tell you the applet is starting. In a more comple" applet! the start method would do things re.uired at the start of the applet such as begin animation or play sounds.
The start Method:

After the start method e"ecutes! the event thread calls the paint method to draw to the applet#s Panel. A thread is a single se.uential flow of control within the applet! and every applet can run in multiple threads. Applet drawing methods are always called from a dedicated drawing and event,handling thread. The stop and destroy Methods: The stop method stops the applet when the applet is no longer on the screen such as when the end user goes to another web page. The e"ample prints a string to the console to tell you the applet is stopping. In a more comple" applet! this method should do things li+e stop animation or sounds. The destroy method is called when the browser e"its. 'our applet should implement this method to do final cleanup such as stop live threads. Appearance The Panel provided in the Applet class inherits a paint method from its parent Container class. To draw something onto the Applet#s Panel! you implement the paintmethod to do the drawing.

The Graphics ob/ect passed to the paint method defines a graphics context for drawing on the Panel. The Graphics ob/ect has methods for graphical operations such as setting drawing colors! and drawing graphics! images! and te"t. The paint method for the SimpleApplet draws the I'm a simple applet string in red inside a blue rectangle.
public void paint(Graphics g ! System"out"println(#Paint# $ %%Set drawing color to blue g"setColor(Color"blue $ %%Speci&y the '( y( width and height &or a rectangle g"draw)ect(*( *( getSi+e( "width ,-( getSi+e( "height ,- $ %%Set drawing color to red g"setColor(Color"red $ %%.raw the te't string at the (-/( 0/ ',y location g"drawString(te't( -/( 0/ $ 1

The Structure of an Applet


A Java applet produces ob/ect code which can be interpreted within the user#s browser. This means that naive users do not have to fuss with program installation. Applets also provide security by restricting local user resource access. Applets can be useful! user friendly programs as demoed by ChemJava or a lot of fun as seen on Jigzone. &ere is the e"planation of the basic structure of a Java applet using the one that you wrote to test your wor+ing environment. Applets are placed in 0&T$1 documents and are e"ecuted from within a Java aware browser. 23 The &ello4orld class implements an applet that displays 5&ello 4orld65 within an 0&T$1 document. 32 import /ava.awt.37 import /ava.applet.37 public class &ello4orld e"tends Applet 8 public void init( 22 Initiali-e the canvas 8 %olor lightgray9new %olor(:;;!:;;!:;; 7 22 customi-e set<ac+ground(lightgray 7 22 ma+e mellow bac+ground

resi-e(;=>!;> 7 ? public void paint(Graphics g 22 @isplay &ello 4orld6 8 g.drawAtring(5&ello 4orld65!=>!:= 7 ? ? 1ine three uses the reserved word import which indicates that ob/ects from e"ternal libraries awt and applet are going to be used. 1ine four uses the reserved word extends to indicate that the class being created is a subclass of the Applet class. This demonstrates how Java code is reused and extended. Note: The JApplet class is used instead of Applet whenever S ing !"# is used. 1ine si" starts the override (change of the /ava.applet.Applet class init() method. 1ine eleven invo+es the resize()method of the Applet ob/ect and sets the window dimensions. )ote the all important statement ending semicolon. 1ine ;: is another method override declaration. This time it is the paint() method of the Applet ob/ect. It is being passed an ob/ect of the Graphics class called g. 1ine ;B tells the Graphics ob/ect g to invo+e its method drawString()using the string 5&ello 4orld6 and position it at point (=>!:= in the previously assigned window. A later tutorial gives details on graphics programming within applets.

Throwing an exception in Java


In our discussion of exceptions in Java, we've so far treated exceptions as being mysteriously thrown at some point, and focussed on the process of catching or handling them. In some cases, exceptions are indeed "magically" thrown by the system. Various exceptions are thrown at the bytecode or system level, such as when an integer division by zero is attempted, when an attempt is made to access an invalid array index, or when Java's ob ect allocator runs out of heap memory. !owever, a program can also deliberately throw an exception. "any exceptions that occur are deliberately thrown by Java library code or by user code when they detect a particular error condition. #o throw an exception, the throw $eyword is used, followed by the exception ob ect to be thrown. #he most common case is to create the

exception ob ect on the fly, so that the code to throw an exception loo$s as follows%
throw new 2O3'ception(#Some re4uired &iles are missing# $

&e can create an instance of any public exception class from the libraries, or we can create our own exception subclass.

Some commonly thrown exceptions


#here are certain exceptions that it is common and good practice to throw at the beginning of a method. #hey are basically unchec$ed exceptions% that is, our method doesn't need to state that it throws these exceptions. #hey can ust be thrown at any time in any method%
IllegalArgumentException

public int calculate5actorial(int n ! i& (n 6 * throw new 2llegalArgument3'ception(#n must be positive# $ i& (n 78 9* throw new 2llegalArgument3'ception(#n must be 6 9*# $ """ 1 NullPointerException If you $now that a parameter to your method cannot be null, then it is best to explicitly chec$ for null and throw a:ullPointer3'ception. #hat way, the problem is detected "there

If your method only accepts arguments within a particular range, e.g. only positive numbers, then you should chec$ for invalid parameters and throw an 2llegalArgument3'ception. 'or example%

and then", rather than at some mysterious point further down when part of your code tries to access the ob ect in (uestion.
IllegalStateException

#his one is a little less common, but is useful a method relies on a previous method having been called. 'or example, if your ob ect re(uires its initialise( method to be called before other methods, then you can set a flag inside initialise( , and throw an2llegalState3'ception if initialise( hasn't been called%
private boolean initted$

public void initialise( ! %% """ initted 8 true$ 1 public void doSomething( ! i& (;initted throw new 2llegalState3'ception(#Object not initialised# $ 1 UnsupportedOperationException

#his exception is designed for cases where you override an abstract class or implement an interface, but don't want or can't to implement certain methods. It is used by various classes of the Java )ollections 'ramewor$. Ideally, your interface or method should also provide a means for the caller to determine in advance whether it expects the given operation to be supported. RuntimeException and InternalError #hese essentially mean "that should never happen and I don't $now what to do if it does", with different degrees of seriousness. *ou basically want the application to "bomb out" of whatever it's doing at that moment. If essentially the application can go on wor$ing after the unexpected condition, throw a )untime3'ception. #hrow an 2nternal3rror in cases where "this is a very serious unexpected condition"% the application is not expected to continue wor$ing and should shut down as soon and safely as possible. #hese exceptions are useful with the techni(ue of recasting, where we turn a normal exception into another that represents a serious condition. "any other exceptions are regular "chec$ed" exceptions +see the exception hierarchy for more details,, which means that if your method throws it, you will have to declare it with throws in the method signature%
public void process5ile(5ile & thro s IOException ! i& (&"length( 7 <A=>?3:G@A thro ne IOException!"#ile too $ig"%& """ 1

-e careful not to confuse throw and throws.

Throwing Exceptions in C#
by Richard Carr, published at http://www.blackwasp.co.uk/CSharpThrowingExceptions.aspx

The thirty-fifth part of the C# Fundamentals tutorial completes an investigation of exception handling. In this article we will consider the throwing of exceptions to report error conditions. This includes the use of standard and custom exception types.
Previous: C# Exception Handling Download Source Code

Why Throw Exceptions


!n the pre"ious part o# the C$ %unda&entals tutorial, ! introduced exception handling and the #acility to catch exceptions using the try / catch / finally bloc in C$. 'uring nor&al processing, it is possible #or an error condition to be detected. !n older languages you &ight exit the #ailing subroutine early and pro"ide a return code to indicate the status. This is possible with C$ but does not take ad"antage

o# the exception handling #eatures pro"ided by the language. !t is pre#erable to raise or throw exceptions explicitly when error conditions occur and allow exceptions to be captured by a try / catch / #inally block or by the C$ runti&e syste&. (ou should throw exceptions only when an unexpected or in"alid acti"ity occurs that pre"ents a &ethod #ro& co&pleting its nor&al #unction) exception handling should not be used #or nor&al progra& #low instead o# conditional processing. !t can be di##icult to &aintain code that &isuses exception handling. *ood uses o# exceptions include:

throwing an exception when an in"alid para&eter "alue is passed to a &ethod. The !rgument"xception or one o# its deri"ed exception classes should be thrown in this situation. throwing an exception when a call is &ade to a &ethod that cannot operate because other steps &ust be taken be#orehand. +n Invalid#peration"xception could be thrown in this case.

Throwing an Exception
To raise an exception you use the throw co&&and. The syntax is as #ollows:
throw exception$

The exception is an exception ob,ect containing the details o# the error being raised. This can be declared as an ob,ect and initialised be#ore the throw co&&and or included in the throw state&ent, using the new keyword and one o# the exception-sconstructors to set the ob,ect-s properties. The #ollowing exa&ple uses a console application that re.uires at least one start/ up para&eter in order to operate. !# no start/up para&eter is pro"ided, an !rgument"xception is thrown. The constructor has a single string para&eter containing the error &essage.
using System$ namespace BlackBasp ! class @estApp ! static void <ain(stringCD args ! %% Check that a parameter was provided i& (args"?ength 88 * ! throw new Argument3'ception(#A start,up parameter is re4uired"# $ 1 1 1 1 Console"Brite?ine(#!*1 argument(s provided#( args"?ength $

When started with a para&eter, the progra& runs without error and outputs the nu&ber o# para&eters pro"ided. !# no argu&ents are speci#ied the body o# the if

statement throws an exception. This a"oids unexpected exceptions occurring later due to the para&eters being in"alid. $%& The class of exception ob'ect to throw should be appropriate for the error condition. "ach exception ob'ect has constructors that may differ from that shown above. For details of other standard exception classes visit the (ystem "xceptions )ierarchy page of *icrosoft+s *(,$ web site.

Thro ing an Exception


#o throw an exception, you use the throw $eyword. #he primary formula of using this $eyword is% try ! Normal flow When to throw the exception throw What? 1 catch(3'ception e ! %% .eal with the e'ception here 1 #he new $eyword in this formula is throw. /n the right side of throw, indicate to the compilerwhat to do. #his means that the throw $eyword is followed by an expression. &e will see various examples. In our introduction to exceptions, we got ac(uainted with the 0xception class. -esides the default constructor, the Exception class is e(uipped with another constructor that ta$es a string as argument. &hen using the throw $eyword, you can use this constructor to specify a message to display to display in case of an error. #o do this, use the new operator to call the constructor and pass a message to it. !ere is an example% import java"util"Scanner$ public class 3'ercise ! public static void main(StringCD args ! int studentAge 8 *$ Scanner scnr 8 new Scanner(System"in $ try ! System"out"print(#Student AgeE # $ studentAge 8 scnr"ne't2nt( $ i&( studentAge 6 * throw new 3'ception(#Positive :umber )e4uired# $ System"out"println(#Student AgeE # F studentAge $

1 catch(3'ception e'c ! System"out"println(#3rrorE # F e'c"get<essage( 1 1

1 #his program starts with the try bloc$ that as$s the user to enter a positive number. If the user enters an invalid value, the program examines the throw $eyword. #his throw appears to display a string. #he compiler registers this string and since there was an exception, the program exits the try bloc$ +it gets out of the try bloc$ even if the rest of the try bloc$ is fine, and loo$s for the first catch bloc$ it can find. If it finds a catch that does not ta$e an argument, it would still use the catch. /therwise, you can use the catch bloc$ to display the error string that was sent by the throw $eyword.

Thread execution
A thread is a thread of e"ecution in a program. The Java Cirtual $achine allows an application to have multiple threads of e"ecution running concurrently. *very thread has a priority. Threads with higher priority are e"ecuted in preference to threads with lower priority. *ach thread may or may not also be mar+ed as a daemon. 4hen code running in some thread creates a new @hread ob/ect! the new thread has its priority initially set e.ual to the priority of the creating thread! and is a daemon thread if and only if the creating thread is a daemon. 4hen a Java Cirtual $achine starts up! there is usually a single non,daemon thread (which typically calls the method named main of some designated class . The Java Cirtual $achine continues to e"ecute threads until either of the following occursD

The e'it method of class )untime has been called and the security manager has permitted the e"it operation to ta+e place. All threads that are not daemon threads have died! either by returning from the call to the run method or by throwing an e"ception that propagates beyond the run method.

There are two ways to create a new thread of e"ecution. Ene is to declare a class to be a subclass of @hread. This subclass should override the run method of class @hread. An instance of the subclass can then be allocated and started. (or e"ample! a thread that computes primes larger than a stated value could be written as followsD
class Prime@hread e'tends @hread ! long minPrime$ Prime@hread(long minPrime !

this"minPrime 8 minPrime$

public void run( ! %% compute primes larger than minPrime " " " 1

The following code would then create a thread and start it runningD
Prime@hread p 8 new Prime@hread(-GH $ p"start( $

The other way to create a thread is to declare a class that implements the )unnable interface. That class then implements the run method. An instance of the class can then be allocated! passed as an argument when creating @hread! and started. The same e"ample in this other style loo+s li+e the followingD
class Prime)un implements )unnable ! long minPrime$ Prime)un(long minPrime ! this"minPrime 8 minPrime$ 1 public void run( ! %% compute primes larger than minPrime " " " 1

The following code would then create a thread and start it runningD
Prime)un p 8 new Prime)un(-GH $ new @hread(p "start( $

*very thread has a name for identification purposes. $ore than one thread may have the same name. If a name is not sp
Si&ply put, a thread is a progra&-s path o# execution. 0ost progra&s written today run as a single thread, causing proble&s when &ultiple e"ents or actions need to occur at the sa&e ti&e. 1et-s say, #or exa&ple, a progra& is not capable o# drawing pictures while reading keystrokes. The progra& &ust gi"e its #ull attention to the keyboard input lacking the ability to handle &ore than one e"ent at a ti&e. The ideal solution to this proble& is the sea&less

execution o# two or &ore sections o# a progra& at the sa&e ti&e. Threads allows us to do this.
Learning about Java threads

This article is part o# the 2a"aWorld technical content archi"e. See the #ollowing to learn &ore about 2a"a threads and concurrency: nderstanding Java threads 3-ava ./. series, 45546:

7art 8: !ntroducing threads and runnables 7art 4: Thread synchroni9ation 7art :: Thread scheduling and wait/noti#y 7art ;: Thread groups and "olatility

!elated articles

<yper/threaded 2a"a: =sing the 2a"a Concurrency +7! 3455>6 ?etter &onitors #or &ultithreaded progra&s 3455@6 =nderstanding +ctor concurrency, 7art 8 3455A6 <anging thread detection and handling 345886

+lso check the 2a"aWorld site "ap and search engine. 0ultithreaded applications deli"er their potent power by running &any threads concurrently within a single progra&. %ro& a logical point o# "iew, &ultithreading &eans &ultiple lines o# a single progra& can be executed at the sa&e ti&e, howe"er, it is not the sa&e as starting a progra& twice and saying that there are &ultiple lines o# a progra& being executed at the sa&e ti&e. !n this case, the operating syste& is treating the progra&s as two separate and distinct processes. =nder =nix, #orking a process creates a child process with a di##erent address space #or both code and data. <owe"er, &ork( creates a lot o# o"erhead #or the operating syste&, &aking it a "ery C7=/intensi"e operation. ?y starting a thread instead, an e##icient path o# execution is created while still sharing the original data area #ro& the parent. The idea o# sharing the data area is "ery bene#icial, but brings up so&e areas o# concern that we-ll discuss later. Creating threads 2a"a-s creators ha"e graciously designed two ways o# creating threads: i&ple&enting an inter#ace and extending a class. Extending a class is the way 2a"a inherits &ethods and "ariables #ro& a parent class. !n this case, one can only extend or inherit #ro& a single parent class. This li&itation within 2a"a can be o"erco&e by i&ple&enting inter#aces, which is the &ost co&&on way to create threads. 3Bote that the act o# inheriting &erely allows the class to be run as a thread. !t is up to the class to start( execution, etc.6

!nter#aces pro"ide a way #or progra&&ers to lay the groundwork o# a class. They are used to design the re.uire&ents #or a set o# classes to i&ple&ent. The inter#ace sets e"erything up, and the class or classes that i&ple&ent the inter#ace do all the work. The di##erent set o# classes that i&ple&ent the inter#ace ha"e to #ollow the sa&e rules.

Character and B$te Streams 4hen dealing with input2output! you have to +eep in mind that there are two broad categories of dataD machine,formatted data and human,readable te"t. $achine,formatted data is represented in binary form! the same way that data is represented inside the computer! that is! as strings of -eros and ones. &uman, readable data is in the form of characters. 4hen you read a number such asH"-G-/I09/G! you are reading a se.uence of characters and interpreting them as a number. The same number would be represented in the computer as a bit,string that you would find unrecogni-able. To deal with the two broad categories of data representation! Java has two broad categories of streamsD byte streams for machine,formatted data and character streams for human,readable data. There are many predefined classes that represent streams of each type. An ob/ect that outputs data to a byte stream belongs to one of the subclasses of the abstract class OutputStream. Eb/ects that read data from a byte stream belong to subclasses of InputStream. If you write numbers to an OutputStream! you won#t be able to read the resulting data yourself. <ut the data can be read bac+ into the computer with an InputStream. The writing and reading of the data will be very efficient! since there is no translation involvedD the bits that are used to represent the data inside the computer are simply copied to and from the streams. (or reading and writing human,readable character data! the main classes are the abstract classes Reader and Writer. All character stream classes are subclasses of one of these. If a number is to be written to a Writer stream! the computer must translate it into a human,readable se.uence of characters that represents that number. Feading a number from a Reader stream into a numeric variable also involves a translation! from a character se.uence into the appropriate bit string. (*ven if the data you are wor+ing with consists of characters in the first place! such as words from a te"t editor! there might still be some translation. %haracters are stored in the computer as ;G,bit Unicode values. (or people who use 4estern alphabets! character data is generally stored in files in AA%II code! which uses only H bits per character. The Reader and Writer classes ta+e care

of this translation! and can also handle non,western alphabets in countries that use them. <yte streams can be useful for direct machine,to,machine communication! and they can sometimes be useful for storing data in files! especially when large amounts of data need to be stored efficiently! such as in large databases. &owever! binary data is fragile in the sense that its meaning is not self,evident. 4hen faced with a long series of -eros and ones! you have to +now what information it is meant to represent and how that information is encoded before you will be able to interpret it. Ef course! the same is true to some e"tent for character data! which is itself coded into binary form. <ut the binary encoding of character data has been standardi-ed and is well understood! and data e"pressed in character form can be made meaningful to human readers. The current trend seems to be towards increased use of character data! represented in a way that will ma+e its meaning as self,evident as possible. 4e#ll loo+ at one way this is done in Aection ;;.=. I should note that the original version of Java did not have character streams! and that for AA%II,encoded character data! byte streams are largely interchangeable with character streams. In fact! the standard input and output streams! System"in and System"out! are byte streams rather than character streams. &owever! you should use Readers and Writers rather than InputStreams andOutputStreams when wor+ing with character data! even when wor+ing with the standard AA%II character set. The standard stream classes discussed in this section are defined in the pac+age java"io! along with several supporting classes. 'ou must import the classes from this pac+age if you want to use them in your program. That means either importing individual classes or putting the directive 5import java"io"J$5 at the beginning of your source file. Atreams are necessary for wor+ing with files and for doing communication over a networ+. They can also be used for communication between two concurrently running threads! and there are stream classes for reading and writing data stored in the computer#s memory. The beauty of the stream abstraction is that it is as easy to write data to a file or to send data over a networ+ as it is to print information on the screen.

The basic I2E classes Reader! Writer! InputStream! and OutputStream provide only very primitive I2E operations. (or e"ample! the InputStream class declares the instance method
public int read( throws 2O3'ception

for reading one byte of data! as a number in the range > to :==! from an input stream. If the end of the input stream is encountered! the read( method will return the value ,; instead. If some error occurs during the input attempt! an e"ception of type IOException is thrown. Aince IOException is an e"ception class that re.uires mandatory e"ception,handling! this means that you can#t use theread( method e"cept inside a try statement or in a subroutine that is itself declared with a 5throws 2O3'ception5 clause. ($andatory e"ception handling was covered in Aubsection H.I.I. The InputStream class also defines methods for reading multiple bytes of data in one step into an array of bytes. &owever! InputStream provides no convenient methods for reading other types of data! such as int or double! from a stream. This is not a problem because you#ll never use an ob/ect of type InputStream itself. Instead! you#ll use subclasses of InputStream that add more convenient input methods to InputStream's rather primitive capabilities. Aimilarly! the OutputStream class defines a primitive output method for writing one byte of data to an output stream. The method is defined asD
public void write(int b throws 2O3'ception

The parameter is of type int rather than byte! but the parameter value is type, cast to type byte before it is written7 this effectively discards all but the eight low order bits of b. Again! in practice! you will almost always use higher,level output operations defined in some subclass of OutputStream. The Reader and Writer classes provide the analogous low, level read and write methods. As in the byte stream classes! the parameter of the write(c method in Writer and the return value of the read( method in Reader are of type int! but in these character,oriented classes! the I2E operations read and write characters rather than bytes. The return value of read( is ,- if the end of the input stream has been reached. Etherwise! the return value must be type,cast to type char to obtain the character that was read. In practice! you will ordinarily use higher level I2E operations provided by sub,classes of Reader and Writer! as discussed below.

#verloading Java $ethods

7osted on %ebruary 85, 4588

%verloading a method is using a method with same name but with different set of arguments and optionally different return type. An *"ample for overloaded method ,
*public class Kehicle!

*0

public void horn( !

*H

System"out"println(#Generic Kehicle blaring its generic horn# $

*G

*/

*9

*L

public class Car e'tends Kehicle !

*M

NOverride

*I

public void horn( !

-*

System"out"println(#A Car blaring its horn# $

--

-0

-H

%%Overloaded method

-G

public void horn(int intensity !

-/

System"out"println(#Car blaring its horn at #FintensityF#dB"# $

-9

-L

In the above code we can see that the class %ar is a subclass of Cehicle. )ow! Cehicle has a generic implementation of the method horn( . This method is overridden by the %ar class to implement car specific horn. 4e also have one more method horn( but with an integer argument JintensityK. This method is said to be overloaded. There are a few +ey points that need to be ta+en care of when Everloading methods.
*public class <ainClass!

*0

public static void main(String argsCD !

*H

%%case -

*G

Kehicle v 8 new Kehicle( $

*/

v"horn( $

*9

v"horn(H* $

*L

%%case 0

*M

Kehicle a 8 new Car( $

*I

a"horn( $

-*

a"horn(L* $

--

%%case H

-0

Car c 8 new Car( $

-H

c"horn( $

-G

c"horn(-** $

-/

%%case G

-9

Car d 8 new Kehicle( $

-L

d"horn( $

-M

-I

En e"ecution both case ; and case : result in compilation error because the reference type of the variable being Cehicle! the method horn( is not overloaded with an integer argument in the Cehicle class but in the %ar class as the methods that are available for access by a variable depend on the reference type of the variable. In the third case! the variable c is an instance of class %ar and is referenced by the same class. &ence going by the e"planation given in the above point! both the statements get e"ecuted resulting in an output of JA %ar blaring its hornK and J%ar is blaring its horn at ;>>d<K.

As mentioned in the previous post! this case results in compilation error. Aome more points to be observed are L

The argument list of the overloaded method must change from the original method. The return type and the e"ceptions declared by the overloaded method can change from the original method. The overloaded method can change the access specifier. Everloading a method can be done in the same class or its subclass.

An important point to note here is that the choice of which overloaded method is e"ecuted depends on the reference type of the variable calling the method! which is decided during the compilation time itself. This is unli+e overridden methods where the choice of the method to be called depends on the ob/ect type and is decided during run time.

You might also like