A Little More Java ObjectOriented Approach - PowerPoint PPT Presentation

1 / 69
About This Presentation
Title:

A Little More Java ObjectOriented Approach

Description:

Consider how a theoretical class called Jabberwock could be created. ... If the jabberwock is not hungry, a message is displayed that the monster already ... – PowerPoint PPT presentation

Number of Views:90
Avg rating:3.0/5.0
Slides: 70
Provided by: walterma
Category:

less

Transcript and Presenter's Notes

Title: A Little More Java ObjectOriented Approach


1
A Little More JavaObject-Oriented Approach
  • Based on lectures by Walter Makovoz, Ph.D.

2
Java Buzzwords
  • Abstract Window Toolkit (AWT) a class library
    (see below) that handles common interface
    elements for windowing interfaces, including
    Windows, and the Macintosh.
  • Applet a program written in Java and intended to
    run with the aid of a Web browser.
  • Bytecode the form of Java code that the Java
    Virtual Machine reads. Developers writing in
    languages such as C use tools called compilers
    to translate their code into native, or machine,
    code. Java compilers instead turn Java programs
    into the intermediate form called bytecode. This
    is slower than compiled code but isn't linked to
    any particular hardware.

3
Java Buzzwords
  • Class defines characteristics for a group of
    objects in object-oriented parlance. Class
    libraries are collections of related classes that
    solve specific programming problems.
  • Java Virtual Machine software that acts like a
    mini-PC, interpreting the Java code so that the
    PC itself doesn't have to. A single Java applet
    or application can run unmodified on any
    operating system that has a virtual machine, or
    VM. Sun writes a virtual machine that it licenses
    to other companies, but operating system vendors
    such as Microsoft generally write their own.
  • (JDK) Sun's free tool for making Java applets
    and full-scale applications. The JDK is a useful
    collection of Java development tools and
    documentation for all levels of Java programmers.
    Sun also rolls out new Java technologies and
    fixes in its upgrades of the JDK. All Java
    licensees are contractually obligated to support
    these changes.

4
Java Buzzwords
  • Java DataBase Connectivity (JDBC) an interface
    that lets Java programs get data from any
    database. The database vendors choose to support
    Java by throwing a JDBC driver into their
    software.
  • JavaBeans Java components designed to perform a
    single function but that can then be mixed and
    matched to build complex applications. They are
    often called just beans.
  • Javascript a Web-scripting language that is used
    in both browsers and Web servers. It is only
    loosely related to Java, and the name causes
    unnecessary confusion. Like any scripting
    language, it's used mostly to tie other
    components together or to accept user input. It
    can work with Java applets with scripting
    interfaces but does not use the same language.

5
Java Buzzwords
  • Just-in-time compiler (JIT) Bytecode is more
    portable but slower than native machine code. To
    try to make applets run faster, just-in-time
    compilers from Sun and several other companies
    translate the bytecode into machine code. But
    while regular compilers do their work before the
    user ever sees the software, just-in-time
    compilers work only after the user downloads an
    applet. JITs also don't change the original code.
    This keeps an applet portable while providing
    performance improvements, although not as much as
    if the applet were compiled to machine code in
    advance.
  • Object-oriented a method of programming that
    pairs programming tasks and data into reusable
    chunks known as objects. Java is an
    object-oriented programming language, as are
    older languages such as Smalltalk and C.
    Object-oriented code is faster to write, easier
    to fix, and can be more easily recycled for other
    applications.
  • Sandbox the security model used to keep Java
    from running amok on your PC. With a sandbox, an
    applet runs within a confined environment, with
    no way to corrupt data, delete files, or reformat
    your hard drive.

6
Object-Oriented Approach
  • What is all the fuss about objects and
    object-oriented technology? Is it real? Or is it
    hype? Well, the truth is--it's a little bit of
    both. Object-oriented technology does, in fact,
    provide many benefits to software developers and
    their products. However, historically a lot of
    hype has surrounded this technology, causing
    confusion in both managers and programmers alike.
    Many companies fell victim to this hardship (or
    took advantage of it) and claimed that their
    software products were object-oriented when, in
    fact, they weren't.
  • These false claims confused consumers, causing
    widespread misinformation and mistrust of
    object-oriented technology.However, in spite of
    overuse and misuse of the term object-oriented,
    the computer industry is now beginning to
    overcome the hype. Understanding is growing about
    this technology and its benefits.This lesson
    slashes through the hype and explains the key
    concepts behind object-oriented programming,
    design, and development.

7
Object-Oriented Approach
  • Objects
  • An object is a software bundle of variables and
    related methods. Software objects are often used
    to model real-world objects you find in everyday
    life.
  • Messages
  • Software objects interact and communicate with
    each other using messages.
  • Classes
  • A class is a blueprint or prototype that defines
    the variables and the methods common to all
    objects of a certain kind.
  • Inheritance
  • (Or what does my grandmother's money have to do
    with all of this?)A class inherits state and
    behavior from its superclass. Inheritance
    provides a powerful and natural mechanism for
    organizing and structuring software programs.

8
Object-Oriented Approach
  • The hardest thing about Java for many novices to
    master is object-oriented programming.
  • The more you are exposed to it, the more
    comfortable you will become with the idea.
  • This lecture goes through the process of creating
    a class -- the fundamental building block of an
    object-oriented program.

9
Object-Oriented Approach
  • Attributes and Behavior
  • Generally, every class you write in Java is made
    up of two components attributes and behavior.
  • We will learn about each component as it applies
    to a theoretical class called Jabberwock.
  • We will create the Java code to implement a
    representation of a jabberwock -- a dragonlike
    monster from the Lewis Carroll poem Jabberwocky.

10
Object-Oriented Approach
  • Attributes of an Object
  • 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 Jabberwock could be
    created. The attributes of a jabberwock might
    include the following
  • Color red, orange, yellow
  • Sex male, female
  • Appetite full, hungry
  • Attributes of an object also can include other
    information about its state.
  • For example, you could have features for the
    jabberwock's attitude (enraged or calm) or its
    current health (alive or dead).

11
Object-Oriented Approach
  • Attributes are defined by variables in fact, you
    can consider them 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.

12
Object-Oriented Approach
  • 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 may be set when an object is
    created and stay constant throughout the life of
    the object, or they may be able to change at will
    as the program runs.
  • Class variables apply to the class itself and to
    all of its instances.
  • Unlike instance variables, whose values are
    stored in the instance, class variable values are
    stored in the class itself

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

14
Object-Oriented Approach
  • 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. Java
    does not have functions of any kind defined
    outside of classes (unlike C).
  • 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 change its
    state.

15
Object-Oriented Approach
  • For example, consider the swordsman in the poem
    Jabberwocky. When he attacked the jabberwock with
    his vorpal blade, here's what happened
  • "One, two! One, two! And through and through
  • The vorpal blade went snicker-snack!
  • He left it dead, and with its head
  • He went galumphing back."
  • In Java, the swordsman could be created as a
    Knight object.
  • When the swordsman chops the head off the
    jabberwock, it definitely causes a change in the
    jabberwock's internal state.
  • The Knight object would use a method to tell the
    Jabberwock object, "I chopped your head off.
    You're dead."

16
Object-Oriented Approach
  • Just as there are instance and class variables,
    there are also instance and class methods.
  • Instance methods (which are so common they're
    usually just called methods) apply and operate on
    an instance of a class.
  • Class methods apply and operate on a class
    itself.
  • You'll learn more about class methods later on.

17
Object-Oriented Approach
  • Creating a Class
  • We will create a working example of the
    Jabberwock class so that you can see how instance
    variables and methods are defined in a class.
  • We also will create a Java applet that creates a
    new instance of the Jabberwock class, displays
    its instance variables, and modifies one of its
    instance variables. .
  • Note The syntax of this example will not be
    covered in great detail. Don't worry too much if
    you're not completely sure what's going on. All
    you need to focus on in this example are the
    basic parts of the Jabberwock class definition.

18
Object-Oriented Approach
  • We start by creating a basic class definition.
    Enter the following
  • class Jabberwock
  • Congratulations! You now have designed a class.
    Of course, it doesn't do much at the moment, but
    that's a Java class at its simplest.
  • To make Jabberwock more sophisticated, create
    three instance variables for this class.
  • Just below the class Jabberwock line, add the
    following three lines
  • String color
  • String sex
  • boolean hungry

19
Object-Oriented Approach
  • These lines create three instance variables.
  • Two, color and sex, can contain String objects.
    (String is part of that standard class library
    mentioned earlier.)
  • The third, hungry, is a boolean that refers to
    whether the jabberwock is hungry (true) or full
    (false).
  • Note In Java, boolean is a real data type that
    can have the values true or false. Unlike C,
    booleans are not numbers.
  • You can add some behavior to the class by adding
    methods. There are all kinds of things a
    jabberwock can do (claws that bite, jaws that
    catch, and so on), but to keep things short, just
    add one method -- a method to feed the monster.

20
Object-Oriented Approach
  • Add the following lines below the three instance
    variables in your class definition
  • void feedJabberwock(Graphics g, int y)
  • if (hungry true)
  • g.drawString("Yum -- a peasant!", 25, y)
  • hungry false
  • else
  • g.drawString("No, thanks -- already
    ate.", 25, y)
  • // more to come

21
Object-Oriented Approach
  • Note The last line, // more to come, is a
    comment line.
  • Comments are used for the benefit of programmers
    looking at source code to figure out what it's
    doing. Everything from the initial // to the end
    of the line will be ignored by the compiler. In
    this case, the comment is being used as a
    placeholder. We will replace it soon.
  • The feedJabberwock method tests to see whether
    the jabberwock is hungry (in the line if (hungry
    true) .
  • If it is hungry, the jabberwock is fed (much to
    its delight), and the state of hungry is changed
    to false.
  • If the jabberwock is not hungry, a message is
    displayed that the monster already ate.

22
Object-Oriented Approach
  • Here's what your program should look like so far
  • class Jabberwock
  • String color
  • String sex
  • boolean hungry
  • void feedJabberwock(Graphics g, int y)
  • if (hungry true)
  • g.drawString("Yum -- a peasant!", 25,
    y)
  • hungry false
  • else

23
Object-Oriented Approach
  • Before you compile this class, you need to add
    one more method. The showAtts method displays the
    current values of the instance variables in an
    instance of your Jabberwock class. In the
    program, delete the comment line // more to come
    and replace it with the following
  • void showAtts(Graphics g, int y)
  • g.drawString("This is a " sex " " color
  • " jabberwock.", 25, y)
  • if (hungry true)
  • g.drawString("The jabberwock is hungry.",
    25, y20)
  • else
  • g.drawString("The jabberwock is full.",
    25, y20)

24
Object-Oriented Approach
  • The showAtts method displays two lines to the
    screen the sex and color of the Jabberwock
    object, and whether the monster is hungry.
  • At this point, we have a Jabberwock class and
    methods that can be used to modify or display its
    instance variables. To do something with the
    class (for example, to create instances of that
    class and play with them, create the code for a
    Java applet that uses Jabberwock.
  • The listing below shows the full source code for
    Jabberwock.java. Return to the Source Editor and
    enter lines 1 through 20 in front of the source
    code you already have entered. When you're done,
    save the program.
  • Caution It is important to note that Java is
    case-sensitive. In this example, if you enter
    g.drawstring as a method name instead of
    g.drawString, it will result as a compiler error
    because drawstring will not be found in the
    java.awt.Graphics class.

25
Object-Oriented (Listing)
  • Listing JabberwockApplet.java.
  • 1 import java.awt.Graphics
  • 2
  • 3 public class JabberwockApplet extends
    java.applet.Applet
  • 4
  • 5 public void paint(Graphics g)
  • 6 Jabberwock j new Jabberwock()
  • 7 j.color "orange"
  • 8 j.sex "male"
  • 9 j.hungry true
  • 10 g.drawString("Calling showAtts ...",
    5, 50)
  • 11 j.showAtts(g, 70)
  • 12 g.drawString("Feeding the jabberwock
    ...", 5, 110)
  • 13 j.feedJabberwock(g, 130)
  • 14 g.drawString("Calling showAtts ...",
    5, 150)
  • 15 j.showAtts(g, 170)
  • 16 g.drawString("Feeding the jabberwock
    ...", 5, 210)
  • 17 j.feedJabberwock(g, 230)

26
Object-Oriented (Listing)
  • Listing JabberwockApplet.java.
  • 21 class Jabberwock
  • 22 String color
  • 23 String sex
  • 24 boolean hungry
  • 25
  • 26 void feedJabberwock(Graphics g, int y)
  • 27 if (hungry true)
  • 28 g.drawString("Yum -- a peasant!",
    25, y)
  • 29 hungry false
  • 30 else
  • 31 g.drawString("No, thanks --
    already ate.", 25, y)
  • 32
  • 33
  • 34 void showAtts(Graphics g, int y)
  • 35 g.drawString("This is a " sex " "
    color
  • 36 " jabberwock.", 25, y)
  • 37 if (hungry true)

27
Object-Oriented Approach
  • Running the Applet
  • Though most of the code in the Jabberwock class
    definition has been described, the contents of
    the JabberwockApplet class in the listing are
    largely new to you. The lines that involve the
    Jabberwock class will be explained more fully to
    give you an idea of how classes are used.
  • Line 6, Jabberwock j new Jabberwock(), creates
    a new instance of the Jabberwock class and stores
    a reference to it in the variable j. Remember
    that you usually do not operate directly on
    classes in your Java programs. Instead, you
    create objects from those classes and call
    methods in those objects. Lines 7, 8, and 9 set
    the instance variables for the Jabberwock object
    j. The color is set to orange, the sex is set to
    male, and the hungry boolean instance variable is
    set to true.

28
Object-Oriented Approach
  • Running the Applet
  • Line 11 calls the showAtts method, defined in
    your Jabberwock object, with the parameters (g,
    70). (The parameters used here and elsewhere in
    the program determine where text will be
    displayed in the applet. Disregard them for now.)
    The showAtts() method displays the values of the
    instance variables sex and color for the
    Jabberwock object j. It also displays the value
    of the instance variable hungry.
  • Line 13 calls the feedJabberwock() method in
    Jabberwock to feed object j. Jabberwock object j
    is hungry when the applet starts because hungry
    initially is set to true, so the object eats the
    food. As you saw in the feedJabberwock() method
    described previously, the instance variable
    hungry is set to false after the Jabberwock
    object eats.
  • Line 15 calls the showAtts() method again,
    displaying the values of the instance variables
    for a second time. A change in state for hungry
    is shown. Line 17 tries to feed the jabberwock
    again to see what happens. Because Jabberwock
    object j is no longer hungry, the object refuses
    to eat the food.

29
Object-Oriented Approach
  • javac JabberwockApplet.java
  • Create JabberwockApplet.html

30
Web Applet HTML file
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtHello to Everyone!lt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • ltPgtMy Java Applet says
  • ltAPPLET CODE"JabberwockApplet.class" HEIGHT250
    WIDTH350gt
  • ltPREgt
  • ltPgtCalling showAtts ...ltBRgt
  • ltPgt This is a male orange jabberwock.ltBRgt
  • ltPgt The jabberwock is hungry.ltBRgt
  • ltPgtFeeding the jabberwock ...ltBRgt
  • ltPgt Yum -- a peasant!ltBRgt
  • ltPgtCalling showAtts ...ltBRgt
  • ltPgt This is a male orange jabberwock.ltBRgt
  • ltPgt The jabberwock is full.ltBRgt
  • ltPgtFeeding the jabberwock ...ltBRgt
  • ltPgt No, thanks -- already ate.ltBRgt
  • lt/PREgt

31
Object-Oriented Java
  • In classic, procedural programming you try to
    make the real world problem you're attempting to
    solve fit a few, pre-determined data types
    integers, floats, Strings, and arrays perhaps. In
    object oriented programming you create a model
    for a real world system.
  • Classes are programmer-defined types that model
    the parts of the system.
  • A class is a programmer defined type that serves
    as a blueprint for instances of the class.
  • You can still have ints, floats, Strings, and
    arrays but you can also have cars, motorcycles,
    people, buildings, clouds, dogs, angles,
    students, courses, bank accounts, and any other
    type that's important to your problem.

32
Object-Oriented Java
  • Classes specify the data and behavior possessed
    both by themselves and by the objects built from
    them.
  • A class has two parts the fields and the
    methods.
  • Fields describe what the class is.
  • Methods describe what the class does.
  • Using the blueprint provided by a class, you can
    create any number of objects, each of which is
    called an instance of the class.
  • Different objects of the same class have the same
    fields and methods, but the values of the fields
    will in general differ.
  • For example, all humans have eye color but the
    color of each human's eyes can be different from
    others.

33
Object-Oriented Java
  • Objects have the same methods as all other
    objects in the class except in so far as the
    methods depend on the value of the fields and
    arguments to the method.
  • This dichotomy is reflected in the runtime form
    of objects. Every object has a separate block of
    memory to store its fields, but the bytes in the
    actual methods are shared between all objects in
    a class.
  • Another common analogy is that a class is to an
    object as a cookie cutter is to a cookie. One
    cookie cutter can make many cookies. There may be
    only one class, but there can be many objects in
    that class. Each object is an instance of one
    class.

34
Example The Website Class
  • Suppose you need to keep a database of web sites.
    Each site has a name, a URL, and a description.
    In traditional programming languages you'd have
    three different String variables for each web
    site. With a class you combine these into one
    thing like this.
  • class Website
  • String name
  • String url
  • String description
  • These variables (name, url and description) are
    called the member variables, instance variables,
    or fields of the class.

35
Constucting Objects with new
  • class Website
  • String name
  • String url
  • String description
  • To instantiate an object in Java, use the keyword
    new followed by a call to the class's
    constructor. Here's how you'd create a new
    Website variable called w
  • Website w
  • w new Website()
  • The first word, Website, declares the type of the
    variable w. Classes are types and variables of a
    class type need to be declared just like
    variables that are ints or doubles.

36
Constucting Objects with new
  • The equals sign is the assignment operator and
    new is the constructor operator.
  • Finally notice the Website() method. The
    parentheses tell you this is a method and not a
    data type like the website on the left hand side
    of the assignment. This is a constructor, a
    method that creates a new instance of a class.
    You'll learn more about constructors shortly.
    However if you do nothing, then the compiler
    inserts a default constructor that takes no
    arguments.
  • This is often condensed into one line like this
  • Website w new Website()

37
The Member Access Separator
  • class Website
  • String name
  • String url
  • String description
  • Once you've created a website you want to know
    something about it. To access the member
    variables of the website you use the . separator.
    The website class has three fields
  • name
  • url
  • description
  • Therefore if w is a Website object, w has three
    fields as well
  • w.name
  • w.url
  • w.description

38
Java Example
  • Website w new Website()
  • w.name "Cafe Au Lait"
  • w.url "http//www.ucla.edu/java/"
  • w.description "Really cool!"
  • System.out.println(w.name " at " w.url
  • " is " w.description)
  • The . separator selects a specific member of a
    website object by name.

39
Using a website object in a different class
  • class Website
  • String name
  • String url
  • String description
  • The next program creates a new website, sets its
    fields, and prints the result
  • class OOPTest public static void main(String
    args)
  • Website w new Website()
  • w.name "Cafe Au Lait"
  • w.url "http//www.ucla.edu/java/"
  • w.description "really cool!"
  • System.out.println(w.name " at " w.url " is
    " w.description)

40
Using a website object in a different class
  • This program requires not just the OOPTest class
    but also the Website class. To make them work
    together put the website class in a file called
    website.java. Put the OOPTest class in a file
    called OOPTest.java. Put both these files in the
    same directory. Then compile both files in the
    usual way. Finally run OOPTest.
  • For example,
  • javac website.java
  • javac OOPTest.java
  • java OOPTest
  • Cafe Au Lait at http//www.ucla.edu/java/ is
    really cool!
  • Note that Website does not have a main() method
    so you cannot run it. It can exist only when
    called by other programs that do have main()
    methods.

41
Member Variables vs. Local Variables
  • class Website
  • String name // member variable
  • String url // member variable
  • String description // member variable
  • Until now all the programs you've seen quite
    simple in structure. Each had exactly one class.
    This class had a single method, main(), which
    contained all the program logic and variables.
    The variables in those classes were all local to
    the main() method. They could not be accessed by
    anything outside the main() method. These are
    called local variables.

42
Member Variables vs. Local Variables
  • This sort of program is the amoebae of Java.
    Everything the program needs to live is contained
    inside a single cell. It's quite an efficient
    arrangement for small organisms, but it breaks
    down when you want to design something bigger or
    more complex.
  • The name, url and description variables of the
    website class, however, belong to a website
    object, not to any individual method. They are
    defined outside of any methods but inside the
    class and are used in different methods. They are
    called member variables or fields.
  • Member variable, instance variable, and field are
    different words that mean the same thing. Field
    is the preferred term in Java. Member variable is
    the preferred term in C.
  • A member is not the same as a member variable or
    field. Members include both fields and methods.

43
Methods
  • Data types aren't much use unless you can do
    things with them. For this purpose classes have
    methods.
  • Fields say what a class is.
  • Methods say what a class does.
  • The fields and methods of a class are
    collectively referred to as the members of the
    class.
  • The classes you've encountered up till now have
    mostly had a single method, main(). However, in
    general classes can have many different methods
    that do many different things. For instance the
    Website class might have a method to print its
    data. Such a class might look like this program.

44
Methods
  • class Website
  • String name
  • String url
  • String description
  • void print()
  • System.out.println(this.name " at "
    this.url " is " this.description)

45
Methods
  • The fields are the same as before, but now
    there's also a method called print().
  • It begins with the Java keyword void which is the
    return type of the method.
  • Every method must have a return type which will
    either be void or some data type like int, byte,
    float, or String.
  • The return type says what kind of the value will
    be sent back to the calling method when all
    calculations inside the method are finished.
  • If the return type is int, for example, you can
    use the method anywhere you use an int constant.
  • If the return type is void then no value will be
    returned.

46
Methods
  • print is the name of this method.
  • The name is followed by two empty parentheses.
  • Any arguments passed to the method would be
    passed between the parentheses, but this method
    has no arguments.
  • Finally an opening brace ( ) begins the body of
    the method.
  • There is one line of code inside the method.
  • This is the call to System.out.println(), a
    method from the Java class library.
  • Question what are some other methods this class
    might need?
  • Or, another way of putting it, what might you
    want to do with a Website object?

47
Invoking Methods
  • class Website
  • String name
  • String url
  • String description
  • void print()
  • System.out.println(this.name " at "
    this.url " is " this.description)
  • Outside the Website class, you call the print()
    method just like you reference fields, using the
    name of the object you want to print and the .
    separator as demonstrated below

48
Invoking Methods
  • class OOPTest
  • public static void main(String args)
  • Website w new Website()
  • w.name "Cafe Au Lait"
  • w.url "http//www.ucla.edu/java/"
  • w.description "Really cool!"
  • w.print()
  • The print() method is completely enclosed within
    the Website class.
  • Every method in a Java program must belong to a
    class.
  • Unlike C programs, Java programs cannot have a
    method hanging around in global space that does
    everything you forgot to do inside your classes.

49
Implied this
  • class Website
  • String name
  • String url
  • String description
  • void print()
  • System.out.println(name " at " url " is
    "
  • description)
  • Within the Website class, may prefix the field
    names with this. like this.name or this.url.
  • The print() method must be called by a specific
    instance of the Website class, and this instance
    knows what its data is. Or, another way of
    looking at it, the every object has its own
    print() method.

50
Passing Arguments to Methods
  • It's generally considered bad form to access
    fields directly. Instead it is considered good
    object oriented practice to access the fields
    only through methods. This allows you to change
    the implementation of a class without changing
    its interface.
  • Of course before the fields of the Website class
    can be made private a means must be provided to
    set their values. To do this you need to be able
    to send information into the Website class. This
    is done by passing arguments. For example to
    allow other classes to change the value of the
    name field in a Website object, the Website class
    would need this method
  • void setName(String s)
  • this.name s
  • The first line of the method is called its
    signature.

51
Passing Arguments to Methods
  • The signature void setName(String s) indicates
    that setName() returns no value and takes a
    single argument, a String which will be referred
    to as s inside the method.
  • s is a purely formal argument.
  • Java passes method arguments by value, not by
    reference.
  • More than one argument can be passed to a method.
  • If so successive arguments are separated by
    commas.
  • For example
  • void setNameURLDescription(String s1, String s2,
    String s3)
  • this.name s1
  • this.url s2
  • this.description s3

52
Returning Values From Methods
  • It's often useful to have a method return a value
    to the class that called it. This is accomplished
    by the return keyword at the end of a method and
    by declaring the data type that is returned by
    the method at the beginning of the method.
  • For example the following getName() method
    returns the current value of the name field in
    the website class.
  • String getName()
  • return this.name
  • The signature String getName() indicates that
    getName returns a value of type String and takes
    no arguments. Inside the method the line
  • return name
  • returns the String contained in the name field to
    whoever called this method. It is important that
    the type of value returned by the return
    statement match the type declared in the method
    signature. If it does not, the compiler will
    complain.

53
Returning Values From Methods
  • It is not possible to return more than one value
    from a method.
  • You cannot, for example, return the name, url and
    description fields with a single method.
  • You could combine them into an object of some
    kind and return the object.
  • However this would be poor object oriented
    design.
  • The right way to solve this problem is to define
    three separate methods, getName(), getURL(), and
    getDescription(), each of which returns its
    respective value.
  • The next program demonstrates this.

54
Returning Values From Methods
  • class Website
  • String name
  • String url
  • String description
  • String getName()
  • return this.name
  • String getURL()
  • return this.url
  • String getDescription()
  • return this.description
  • void setName(String s)
  • this.name s
  • void setURL(String s)

55
Constructors
  • The first method most classes need is a
    constructor.
  • A constructor creates a new instance of the
    class. It initializes all the variables and does
    any work necessary to prepare the class to be
    used. In the line
  • Website w new Website()
  • Website() is the constructor. A constructor
    method has the same name as the class.
  • If no constructor exists Java provides a generic
    one, but it's better to write your own. You make
    a constructor by writing a method that has the
    same name as the class. Thus the website
    constructor is called Website().
  • Constructors do not have return types. They are
    the only method for which this true. They do
    return an instance of their own class, but this
    is implicit, not explicit.

56
Constructors
  • Better yet, we can create a constructor that
    accepts three Strings as arguments and use those
    to initialize the fields as below.
  • class Website
  • String name
  • String url
  • String description
  • Website(String n, String u, String d)
  • this.name n
  • this.url u
  • this.description d
  • String getName()
  • return this.name

57
Constructors
  • Better yet, we can create a constructor that
    accepts three Strings as arguments and use those
    to initialize the fields as below.
  • String getURL()
  • return this.url
  • String getDescription()
  • return this.description
  • void setName(String s)
  • this.name s
  • void setURL(String s)
  • this.url s

58
Constructors
  • Better yet, we can create a constructor that
    accepts three Strings as arguments and use those
    to initialize the fields as below.
  • void setDescription(String s)
  • this.description s
  • void print()
  • System.out.println(this.name " at "
    this.url " is "
  • this.description)

59
Using Constructors
  • This program uses the constructor instead of the
    set methods to prepare the web site to be
    printed.
  • class OOPTest
  • public static void main(String args)
  • Website w new Website("Cafe Au Lait",
  • "http//www.ucla.edu/java/",
  • "really cool!")
  • w.print()
  • If all you want to do is create new web sites and
    print them, you no longer need to know about the
    fields name, url and description. All you need to
    know is how to construct a new website and how to
    print it.

60
Constructors
  • The following method is a constructor that
    initializes all the fields to empty Strings.
  • Website()
  • this.name ""
  • this.url ""
  • this.description ""

61
Example
  • // what is the print out of the following code
  • import java.awt.
  • import java.applet.Applet
  • class apple
  • int i 1 // a.i 1
  • class inc
  • static int add_one( int i ) i i 1return
    i
  • static void add_one ( apple a )
  • a.i a.i 1
  • public class ref extends Applet
  • public static void main ( string args )
    apple a new apple ( )system.out.println (
    a.i "\t" inc.add_one(a.i) "\t"
    a.i)inc.add_one( a )system.out.println ( a.i
    )

62
Example
  • Answer
  • Class Overloaded methods
  • Object and Classes
  • An object is a combination of code ( functions )
    and data ( variables ) joined together into a
    single entity.
  • A class is essentially a description of how to
    make an object.
  • Every object has a class which is used to
    determine how to create the object, what
    variables the object will contain, and what
    messages the object will respond to.
  • Object have type

63
Example
  • Class Definition
  • class ltclass namegt extends ltclass namegt
    implements ltinterface namegt
  • ltvariable_declarationgtltmethod_declarationgt
  • Example
  • class Lamp
  • boolean on
  • Lamp l new Lamp ( )
  • l.on true

64
Example
  • Overloaded methods
  • Default constructor takes null.
  • Example
  • class Lamp
  • boolean onint Wattage
  • Lamp ( ) // if, Lamp ( int w ) here
  • Wattage 100 // then, Wattage w or Lamp bulb
    new Lamp ( 100 ) here // otherwise, Lamp bulb
    new Lamp ( ) , syntax error

65
Example
  • Class doesn't need methods!
  • Example
  • Class CS410
  • student saint number_of_studentfinal string
    name "programming in Java" // cant be changed
  • CS410( int i )
  • number_of_student i
  • void Print ( )
  • system.out.println(" I have" number_of_student
    " in my class.")
  • Class instance CS410 c.i new CS410(30)
    Static variables propagate to all instances of
    classes.

66
Example
  • Example
  • class Student
  • static int student_count 0
  • void Student ( )
  • student_count
  • Static method a good for grouping utility
    functions.

67
Example
  • class Trig
  • static float area ( float r )
  • return Math.PI r r
  • float A Trig.area(10)
  • Default for numeric fields not explicitly
    initialized is 0.

68
Example
  • A static method cannot make reference to a
    non-static method.
  • class foo
  • static int inc( int i ) return i
  • int wow( int i ) // OK
  • return inc( i )
  • static int wee( int i )
  • return wow( i )

69
Example
  • double negative ( )
  • return Math.SQRT ( x x y y )
  • void Print ( )
  • system.out.println ( this.getclass( ).getname( )
    " " )system.out.println ( x " " y )
Write a Comment
User Comments (0)
About PowerShow.com