An introduction to - PowerPoint PPT Presentation

1 / 47
About This Presentation
Title:

An introduction to

Description:

... problem (in a relatively non-portable fashion, but then that code is isolated) ... An applet called NowShowing.class is loaded from a directory called progdir. ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 48
Provided by: Mik7258
Category:

less

Transcript and Presenter's Notes

Title: An introduction to


1
  • An introduction to
  • Java Applets
  • lecturer Mihai Horia Zaharia

2
  • Objects and Classes
  • Object-oriented programming is modeled on the
    observation that, in the real world, objects are
    made up of many kinds of smaller objects.
  • However, the capability to combine objects is
    only one general aspect of object-oriented
    programming.
  • Object-oriented programming provides several
    other concepts and features to make the creation
    and use of objects easier and more flexible. The
    most important of these features is the class.

3
  • A class is a template for multiple objects with
    similar features. Classes embody all the features
    of a particular set of objects. When you write a
    program in an object-oriented language, you don't
    define individual objects. You define classes of
    objects.
  • For example, you might have a Tree class that
    describes the features of all trees (each tree
    has branches and roots, grows, and creates
    chlorophyll). The Tree class serves as an
    abstract model for the concept of a tree. To
    reach out and grab, or interact with, or cut down
    a tree, you must have a concrete instance of that
    tree.

4
  • Of course, once you have a Tree class, you can
    create lots of different instances of that tree,
    and each different tree instance can have
    different features (it can be short, tall, bushy,
    drop leaves in autumn, and so on), yet still
    behave like a tree and be immediately
    recognizable as one
  • An instance of a class is an actual object of
    that class. The class is the general, abstract
    representation of an object, and an instance is
    its concrete representation. The term object is
    used more generally, but both instances and
    objects are the concrete representations of a
    class.

5
  • If you're used to programming in C, you can think
    of a class as a way to create a new composite
    data type that is analogous to using struct and
    typedef statements in C. Classes, however, can
    provide much more functionality than just a
    collection of data.
  • When you write a Java program, you design and
    construct a set of classes. When your program
    runs, instances of those classes are created and
    discarded as needed.
  • The Java environment comes with a library of
    classes that implement a lot of the basic
    behaviors you need.

6
  • Attributes and Behavior
  • Generally, every class you write in Java is made
    up of two components attributes and behavior.
  • Attributes are the individual things that
    differentiate one object from another and
    determine the appearance, state, or other
    qualities of that object.
  • Consider how a theoretical class called Dog could
    be created. The attributes of a Dog might include
    the following
  • Color red, orange, yellow
  • Sex male, female
  • Appetite full, hungry

7
  • Attributes of an object also can include other
    information about its state. For example, you can
    have features for the dog's attitude (irritated
    or calm) or its current health (alive or dead).
  • Attributes are defined by variables in fact, you
    can consider attributes to be analogous to global
    variables for the entire object.
  • Because each instance of a class can have
    different values for its variables, each variable
    is called an instance variable.
  • Instance variables define the attributes of an
    object. The class defines the type of the
    attribute, and each instance stores its own value
    for that attribute.

8
  • Each attribute, as the term is used here, has a
    single corresponding instance variable changing
    the value of a variable changes the attribute of
    that object.
  • Instance variables can be set when an object is
    created and stay constant throughout the life of
    the object, or they can change at will as the
    program runs.
  • Class variables apply to the class itself and to
    all of its instances. Instance variable values
    are stored in the instance class variable values
    are stored in the class itself.

9
  • How Objects Behave?
  • Behavior is the only way objects can do anything
    to themselves or have anything done to them. The
    behavior of a class determines what instances of
    that class will change their internal state.
  • Behavior also determines what class instances do
    when asked to do something by another class or
    object. For example, the Dog class might have
    some of the following behaviors
  • Get angry
  • Calm down
  • Eat a peasant
  • Skip dinner
  • Recuperate

10
  • To define an object's behavior, you create
    methods. Methods are just like functions in other
    languages, but they are defined inside classes.
    Methods operate on instances of their class.
  • Unlike C, Java does not have functions of any
    kind defined outside of classes.
  • Although methods operate within their own class,
    methods do not affect only a single object.
    Objects communicate with each other using
    methods.
  • A class or object can call methods in another
    class or object to communicate changes in the
    environment or to ask that an object changes its
    state.

11
  • Main differences between C/C and Java
  • Java, like C, has primitive types for efficient
    access. In Java, these are boolean, char, byte,
    short, int, long, float, and double.
  • All the primitive types have specified sizes that
    are machine independent for portability. (This
    must have some impact on performance, varying
    with the machine.)
  • Type-checking and type requirements are much
    tighter in Java. For example
  • Conditional expressions can only be boolean, not
    integral.
  • The result of an expression like X Y must be
    used you cant just say X Y for the side
    effect.

12
  • The char type uses the international 16-bit
    Unicode character set, so it can automatically
    represent most national characters.
  • Java adds the triple right shift gtgtgt to act as a
    logical right shift by inserting zeroes at the
    top end the gtgt inserts the sign bit as it
    shifts.
  • Although they look similar, arrays have a very
    different structure and behavior in Java than
    they do in C.
  • Theres a read-only length member that tells you
    how big the array is, and run-time checking
    throws an exception if you go out of bounds.

13
  • All arrays are created on the heap, and you can
    assign one array to another (the array handle is
    simply copied). The array identifier is a
    first-class object, with all of the methods
    commonly available to all other objects.
  • No forward declarations are necessary in Java. If
    you want to use a class or a method before it is
    defined, you simply use it the compiler ensures
    that the appropriate definition exists.
  • Java has no preprocessor. If you want to use
    classes in another library, you say import and
    the name of the library. There are no
    preprocessor-like macros.

14
  • OOP level differences
  • Java has method overloading, but no operator
    overloading. The String class does use the and
    operators to concatenate strings and String
    expressions use automatic type conversion, but
    thats a special built-in case.
  • Variable scope
  • The class, and each method within the class, has
    an access specifier to determine whether its
    visible outside the file.
  • Sometimes the private keyword is used less in
    Java because friendly access is often more
    useful than excluding access from other classes
    in the same package.

15
  • The Java protected keyword means accessible to
    inheritors and to others in this package.
  • Theres no virtual keyword in Java because all
    non-static methods always use dynamic binding.
  • Instead of virtual Java uses abstract keyword
  • In Java, the programmer doesnt have to decide
    whether to use dynamic binding.

16
  • The final keyword tells the compiler that this
    method cannot be overridden, and thus that it may
    be statically bound (and made inline, thus using
    the equivalent of a C non-virtual call). These
    optimizations are up to the compiler.
  • Instead of controlling blocks of declarations
    like C does, the access specifiers (public,
    private, and protected) are placed on each
    definition for each member of a class.

17
  • The const issues in C are avoided in Java by
    convention. You pass only handles to objects and
    local copies are never made for you
    automatically.
  • If you want the equivalent of Cs
    pass-by-value, you call clone( ) to produce a
    local copy of the argument
  • Theres no copy-constructor thats automatically
    called. To create a compile-time constant value,
    you say, for example
  • static final int SIZE 255
  • static final int BSIZE 8 SIZE

18
  • Classes
  • Everything must be in a class. There are no
    global functions or global data. If you want the
    equivalent of globals, make static methods and
    static data within a class. There are no structs
    or enumerations or unions, only classes.
  • All method definitions are defined in the body of
    the class. Thus, in C it would look like all
    the functions are inlined, but theyre not
    (inlines are noted later).
  • Java has constructors that are similar to
    constructors in C. You get a default
    constructor if you dont define one. There are no
    copy constructors, since all arguments are passed
    by reference.

19
  • There are no destructors in Java. Thats because
    there is no scope of a variable to indicate
    when the objects lifetime is ended. So the
    lifetime of an object is determined instead by
    the garbage collector.
  • There is a finalize( ) method thats a member of
    each class, something like a C destructor, but
    finalize( ) is called by the garbage collector
    and is supposed to be responsible only for
    releasing "resources" (such as open files,
    sockets, ports, URLs, etc).
  • If you need something done at a specific point,
    you must create a special method and call it, not
    rely upon finalize( ).

20
  • All objects in C will be (or rather, should be)
    destroyed, but not all objects in Java are
    garbage collected.
  • Because Java doesnt support destructors, you
    must be careful to create a cleanup method if
    its necessary and to explicitly call all the
    cleanup methods for the base class and member
    objects in your class.
  • Due to garbage collection, memory leaks will have
    a decreased rate of apearance by comparision with
    other compilers, but not zero.
  • If you make native method calls that allocate
    storage, these are typically not tracked by the
    garbage collector.

21
  • However, many memory leaks and resouce leaks can
    appear because of a badly written finalize() or
    because of not releasing a resource at the end of
    the block where it is allocated (a place where a
    destructor would certainly come in handy).
  • The garbage collector is a huge improvement over
    C, and makes a lot of programming problems
    simply vanish.
  • It might make Java unsuitable for solving a small
    subset of problems that cannot tolerate a garbage
    collector, but the advantage of a garbage
    collector seems to greatly outweigh this
    potential drawback

22
  • Inheritance
  • Java uses a single-rooted hierarchy, so all
    objects are ultimately inherited from the root
    class Object. In C, you can start a new
    inheritance tree anywhere, so you end up with a
    forest of trees.
  • Even if Java can seem restrictive, it gives a
    great deal of power since you know that every
    object is guaranteed to have at least the Object
    interface. C appears to be the only OO language
    that does not impose a single rooted hierarchy.

23
  • Java doesnt provide multiple inheritance (MI),
    at least not in the same way that C does.
  • Since Java uses a single-rooted hierarchy, youll
    probably run into fewer situations in which MI is
    necessary. The interface keyword takes care of
    combining multiple interfaces.
  • The rule of single inheritance is that each Java
    class can have only one superclass (although any
    superclass can have multiple subclasses).

24
  • Interfaces
  • Because of single inheritance, any Java class has
    only a single superclass. It inherits variables
    and methods from all superclasses above it in the
    hierarchy. This makes subclassing easier to
    implement and design, but it can also be
    restricting - especially when you have similar
    behavior that must be duplicated across different
    branches of a class hierarchy. Java solves the
    problem of shared behavior by using interfaces.
  • An interface is a collection of method names,
    without actual definitions, which indicate that a
    class has a set of behaviors in addition to the
    behaviors it receives from its superclasses.

25
  • Although a single Java class can have only one
    superclass, the superclass can also implement any
    number of interfaces.
  • By implementing an interface, a class provides
    method definitions for the method names defined
    by the interface.
  • If two very different classes implement the same
    interface, they both can respond to the same
    method calls as defined by that interface.
    However, what each class does in response to
    those method calls can be completely different.

26
  • Libraries level
  • Since Java can be too restrictive in some cases,
    you could be prevented from doing important tasks
    such as directly accessing hardware.
  • Java solves this with native methods that allow
    you to call a function written in another
    language (currently only C and C are
    supported).
  • Thus, you can always solve a platform-specific
    problem (in a relatively non-portable fashion,
    but then that code is isolated). Applets cannot
    call native methods, only applications.

27
  • Exception specifications in Java are superior to
    those in C. Instead of the C approach of
    calling a function at run-time when the wrong
    exception is thrown, Java exception
    specifications are checked and enforced at
    compile-time.
  • In addition, overridden methods must conform to
    the exception specification of the base-class
    version of that method they can throw the
    specified exceptions or exceptions derived from
    those. This provides much more robust
    exception-handling code.

28
  • Exception handling in Java is different because
    there are no destructors. A finally clause can be
    added to force execution of statements that
    perform necessary cleanup. All exceptions in Java
    are inherited from the base class Throwable, so
    youre guaranteed a common interface.
  • public void f(Obj b) throws IOException
  • myresource mr b.createResource()
  • try mr.UseResource()
  • catch (MyException e) // handle this exception
  • finally
  • mr.dispose() // special cleanup

29
  • Applet Methods
  • The structure of an applet takes the form of five
    events that can take place as an applet is
    running. When the events occur, a method is
    automatically called. The methods also can be
    called directly within the applet. The methods
    are the following
  • Initialization The init() method is called the
    first time the applet is loaded.
  • Destruction The destroy() method is called the
    final time the applet is exited.
  • Stopping The stop() method is called each time
    an applet is stopped. A stop happens
    automatically when a Web page containing the
    applet is exited and also when the stop() method
    is called directly in a program.

30
  • Starting The start() method is called each time
    an applet is loaded or reloaded. A start follows
    initialization and also takes place each time the
    applet is restarted. A start happens when a Web
    user comes back to the applet's page after
    leaving it you can also call start() directly.
  • Painting The paint()method is called any time
    the applet window must be repainted. This occurs
    automatically at certain times, such as when the
    applet window is covered up by another window and
    then uncovered. It also can be called by using a
    repaint() call when a program needs a screen
    update to take place.

31
  • The last of the methods, paint(), must take a
    parameter - an instance of the Graphics class -
    as in the following method definition
  • public void paint(Graphics g)
  • g.drawString("One moment, please", 5, 50)
  • A Graphics object is used to indicate where
    something should be drawn.
  • The Graphics object used as the parameter to
    paint() is created automatically, and it
    represents the applet window.
  • The g.drawString() line uses this Graphics object
    to indicate where a string should be drawn.

32
  • Every time the repaint() method is called and the
    applet window must be updated, the string is
    drawn at the x, y position (in this example, 5,
    50).
  • The Graphics object does not have to be declared.
    However, the Graphics class must be imported at
    the beginning of an applet's source code.
  • Each of these applet methods-init(), destroy(),
    start(), stop(), and paint()-is inherited by an
    applet. You do not have to write your own methods
    for any of these.
  • However, each of the applet methods is empty by
    default. If something is supposed to happen in an
    applet, some or all of these methods must be
    overridden.

33
  • The ltAPPLETgt Tag
  • For a Java applet to be run when a Web page is
    loaded, information about that applet must be put
    on the page. This requires the use of two special
    HTML tags ltAPPLETgt and ltPARAMgt.
  • This HTML code is included on a Web page along
    with all other HTML code. In this respect,
    putting a Java applet on your home page is no
    different than putting a picture there.
  • Java applets can be viewed by Web browsers and
    any other software that is equipped to load
    applets, such as the applet viewer utility that
    comes with the Java Developers Kit.
  • Following is an example of an applet tag

34
  • ltAPPLET CODE"NowShowing.class
    CODEBASE"progdir" WIDTH376 HEIGHT104gt
  • An applet called NowShowing.class is loaded from
    a directory called progdir.
  • The CODE attribute specifies the applet to load,
    and the optional CODEBASE attribute refers to a
    directory where the applet can be found.
  • The applet is set to a width of 376 pixels and a
    height of 104 pixels using the WIDTH and HEIGHT
    attributes.
  • ltPARAM NAME"speed" value"100"gt
  • ltPARAM NAME"blink" value"5"gt
  • ltPARAM NAME"text" value"FREE DANCER"gt
  • ltPARAM NAME"fontsize" value"21"gt
  • ltPARAM NAME"pattern" value"random"gt

35
  • Five parameters are sent to the applet speed,
    blink, text, fontsize, and pattern.Parameters are
    optional you can include as many as you want.
  • The NAME attribute indicates the name a parameter
    should be given, and the VALUE attribute
    indicates the value to associate with the
    parameter.
  • ltH5gtThis applet requires the use of a
    Java-enabled browser!lt/H5gt this is only printed
    if the applet is not supported
  • lt/APPLETgt
  • Browsers that do not handle Java programs
    disregard everything within the ltAPPLETgt,
    lt/APPLETgt, and ltPARAMgt tags. As shown in the
    preceding HTML code of an applet tag, an
    alternative can be provided for browsers that do
    not handle Java.

36
  • The CODE attribute must be used in conjunction
    with the ltAPPLETgt tag because it specifies the
    name of the applet's class file.
  • This is the file that will be run after it has
    been loaded onto the Web user's computer.
  • If the CODEBASE attribute is used, it indicates
    the path from the Web page's directory to the
    directory containing the applet's class file.
  • For example, CODEBASE"usr" indicates that the
    applet is in a directory called usr that is a
    subdirectory of the Web page's directory.

37
  • If the applet makes use of class files that are
    not part of the standard Java API, these class
    files must be located in the same directory as
    the applet's class file.
  • The HEIGHT and WEIGHT attributes should be
    familiar to anyone who has used them to place an
    image on a Web page - they work the same with
    ltAPPLETgt as they do with ltIMGgt.
  • The ALIGN attribute used with images can also be
    used with ltAPPLETgt. The ALIGN attribute
    determines how the applet is positioned in
    relation to the other parts of the Web page and
    can have the values TOP, MIDDLE, or BOTTOM.

38
  • Using Parameters
  • Parameters can be sent to an applet by using the
    ltPARAMgt tag and its two attributes NAME and
    VALUE. Here's a line from the preceding example
  • ltPARAM NAME"blink" VALUE"100"gt
  • The value of the NAME attribute assigns a name to
    an applet parameter, and VALUE gives the
    parameter a value. The preceding statement sends
    a parameter named blink with a value of 100.
  • Parameters are sent to an applet when it is
    loaded you can send as many parameters as you
    want. All parameters are sent to applets as
    strings and must be converted to other data types
    if they are needed as integers or other types.

39
  • For a parameter to be used by a Java applet, the
    applet must retrieve the parameter. This requires
    the getParameter() method, which is available to
    all applets because it is part of the Applet
    class.
  • For example, use the following line in a Java
    applet to store the blink parameter in a variable
    called blinkValue
  • String blinkValue getParameter("blink")
  • If you want to retrieve the value and convert it
    to an integer, use the following code
  • int blinkValue -1
  • try blinkValue Integer.parseInt(getParameter("
    blink"))
  • catch (NumberFormatException e)

40
  • This example uses the parseInt() method of the
    java.lang.Integer class to convert a String into
    an int. The try and catch block is used to trap
    errors if the String cannot be converted into a
    number.
  • Putting the Applet on the Web
  • When you have created an applet and added it to
    HTML pages, you easily can make it available on
    the World Wide Web.
  • Put all .class files required by the applet on
    your Web site, making sure to put the files in
    the same directory as the CODEBASE attribute if
    it has been used.
  • If not, put the .class files in the same
    directory as the Web page that includes the
    applet.

41
  • Programming the Applet
  • The ColorCycle applet is a simple applet with one
    button labeled Next Color. When the button is
    clicked with the mouse, the background color of
    the applet changes.
  • The program demonstrates basic applet structure
    and a simple bit of event handling how to respond
    to a mouse click on a button.
  • The applet imports several classes by using the
    wildcard character with java.awt.. The awt
    stands for Abstract Windowing Toolkit, the set of
    classes used to handle most visual elements of
    Java programming, graphics, fonts, a user
    interface and also to respond to user input from
    the keyboard and mouse.

42
  • The source code of ColorCycle.java.
  • import java.awt.
  • public class ColorCycle extends
    java.applet.Applet
  • float hue (float).5
  • float saturation (float)1
  • float brightness (float)0
  • Button b
  • Three instance variables are created to store the
    HSB values of the color being displayed.
  • HSB (Hue, Saturation, and Brightness) is a method
    of describing a color as three numeric values
    from 0 to 1.

43
  • public void init()
  • b new Button("Next Color")
  • A Button object is created.
  • add(b)
  • In the init() method of the applet, which is
    called automatically when the applet is first
    run, the Button object b is instantiated and is
    assigned the label Next Color.
  • public void start()
  • setBackground(Color.black)
  • repaint()

44
  • In the start() method of the applet, which is
    called after init() and whenever a Web user
    returns to the page containing the applet, the
    background color of the applet is set to black by
    using the Color constant Color.black.
  • Additionally, a call to the repaint() method
    tells the applet that the window must be redrawn
    because something, in this case the background
    color, has changed.
  • public boolean action(Event evt, Object o)
  • The action() method is called whenever a user
    interface component generates an action event.
  • In this applet, an event occurs when the Next
    Color button is clicked.

45
  • if (brightness lt 1)
  • brightness .25
  • else
  • brightness 0
  • The value of brightness is changed so that the
    background cycles through several colors ranging
    from black to light blue.
  • Color c new
  • Color(Color.HSBtoRGB(hue,
  • saturation, brightness))
  • setBackground
  • repaint()
  • A Color object is created to store the value of
    the background color, which is created based on
    the values of the variables hue, saturation, and
    brightness.
  • The background color is changed and another call
    to repaint() is made.

46
  • return true
  • The boolean value true is returned at the end of
    the action() method, indicating that the action
    event generated by clicking the button was taken
    care of.
  • Designing the HTML Page
  • lthtmlgt
  • ltbodygt
  • ltapplet codeColorCycle.java height250
    width250gt
  • lt/appletgt
  • lt/bodygt
  • lt/htmlgt

47
  • References
  • Mark Wutka, et. al., JAVA Expert Solutions, on
    line
  • Michael Morrison, et al, Java Second Edition, on
    line
  • Bruce Eckel, Thinking in Java, Prentice Hall
    PTR, Upper Saddle River, New Jersey 07458
Write a Comment
User Comments (0)
About PowerShow.com