420 likes | 469 Views
2. Programming with Objects. 2.1 Names 2.2 Objects and Classes 2.3 using Objects 2.4 Arithmetic Expressions 2.5 Parameters and Input 2.6 Getting Started with Applets and Events. Objectives. Name objects and other Java entities Build a class to define objects
E N D
2. Programming with Objects 2.1 Names 2.2 Objects and Classes 2.3 using Objects 2.4 Arithmetic Expressions 2.5 Parameters and Input 2.6 Getting Started with Applets and Events
Objectives • Name objects and other Java entities • Build a class to define objects • Use methods to invoke other behavior • Use arithmetic expressions to compute value • Input in a dialog • Use an import statement • Get started with applet and events
2.1 Names • Objects can communicate by calling each other’s responsibilities by names • Names of objects, their data and responsibilities are called identifiers <identifier> ::= <letter>{<letter> | digit} <letter> ::= a..z | A..Z | _ | $ <digit> ::= 0..9 • Keywords are reserved identifiers for special uses
The (7-bit) ASCII character set contains 128 characters • The (8-bit) Extended ASCII character set contains 256 characters • In general, an n-bit character set contains 2 characters. • Java uses a 16-bit character set called Unicode that may contain at most 65536 characters • Unicode contains ASCII code as a subset, and characters of many countries n
Valid Identifiers savings, textLabel, rest_stop_12, x, I3, _test, $soup Not valid Identifiers 4you // Starts with a number x<y // Includes an illegal character, < top-gun // Includes an illegal character, - int // Reserved, see below Figure 2.2 Valid and Invalid Java identifiers
2.2 Objects and Classes • We can think of an object as a collection of services that we can tell it to perform for us • A class defines a type of objects public class Vending { // variables, methods, and constructors } • Java’s style starts class names with an uppercase character • Starts comment with //(through end of line), or enclose it with /* and */
Java entity Use class define a type of object instance variable define object state instance method define object behavior constructor provide object identity Figure 2.4 Java constructs for defining objects
Variables and their values define the state of an object • A variable can hold either a primitive type or an object reference • Primitive types include byte, short, int, long, float, double, char, and boolean • Java uses 32-bit (signed) integers. The range is -2,147,483,648 to 2,147,483,647 • Accessibility can be controlled by modifiers public, private or protected
Instance variables are those defined in a class without the static modifier • Constructors have the same name as the class • A constructor allocates space for the instance variables and may also initialize their values • A constructor may have formal parameters • Default constructor is one without parameters. • A constructor doesn’t return any value
Methods specify the responsibilities, or behaviors, of the objects • Instance methods are those defined without the static modifier • A method has a header and a body • The header specifies the type, the name, a list of parameters, and other modifiers • The body contains the details to accomplish the designed responsibility or behavior • The body contains a series of declarations and statements
Consider the statement: quarters = quarters + numberOfQuarters;
Packages • Example: package vend; • Java organizes classes into packages • A package name corresponds to a directory of the host file system • Java style starts a package name with lowercase letter • The package statement must be the first non-comment line in the program • The import statement
Some of the packages in the standard class library are: PackagePurpose java.lang General support java.applet Creating applets for the web java.awt Graphic and GUI javax.swing Additional graphic capabilities java.net Network communication java.util Utilities
The assignment statement • The return statement • A string is a sequence of characters. • Constant strings are enclosed in double quotes, e.g. “three blind mice”. • The String class • The void keyword • Unified Modeling Language (UML) object diagram.
___________:Vending1 quarters = 10 candyBars = 15 enterMoney selectMoney Figure 2.6 A Vending1 instance
2.3 Using Objects • A variable whose type is a class is a reference variable to an object Vending1 byTheDoor = new Vending1(10,15); • Reference variable byTheDoor holds the address of the newly created Vending1 object • The decalaration Vending1 machineA; Creates a reference variable referring to no object at this point (with value null)
___________:Vending1 quarters = 10 candyBars = 15 enterMoney selectMoney byTheDoor Figure 2.7 A reference variable of type Vending1
null machineA Figure 2.8 A null reference
An instance method must be invoked via an object reference • Need testing (or driver) class to create objects and invoke their methods • Special method in driver class: public static void main(String[] args) { // code goes here }; • Class methods - declared with static • Java interpreter invokes the class method main to start executing a Java program
___________:Vending1 quarters = 13 candyBars = 15 enterMoney selectMoney byTheDoor Figure 2.9 After executing byTheDoor.enterMoney(3)
___________:Vending1 quarters = 13 candyBars = 14 enterMoney selectMoney byTheDoor Figure 2.10 After executing byTheDoor.selectCandy()
Local variables: those declared inside a method • Output statement: System.out.print(“Have a nice day ”); System.out.println(12345); • System is a class defined in java.lang package, and out is one of its class variable, a reference to a PrintStream object • The PrintStream class has many methods including print and println
2.4 Arithmetic Expressions • An expression is a combination of operators and operands • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder % • If either or both operands are floating point, the result is floating point.
Operation Math notation Java (constants) Java (variables) Addition a + b 3 + 4 score1 + score2 Subtraction a - b 3 - 4 bats - gloves Multiplication ab 12 * 17 twelve * dozens Division a/b 7 / 3 total / quantity Remainder r in a=qb+r 43 % 5 cookies % people Negation -a -6 -amount Figure 2.13 Java arithmetic operations
Operator Precedence • Operators can be combined into complex expressions result = total + count / max - offset; • Operators have a well-defined precedence which determines the order of evaluation • Multiplication, division, and remainder are evaluated prior to addition, subtraction and string concatenation • Arithmetic operators with same precedence are evaluated from left to right • Parentheses can be use to change the order
4 * 5 3 + Figure 2.14 Multiplication gets its operands first
(3 + 4) * 5 Figure 2.15 Compute within parentheses first
Increment & Decrement Operators • The increment and decrement operators are unary • The increment operator (++) adds one to its operand • The decrement operator (--) subtracts one from its operand • The statement count++; is essentially equivalent to count = count + 1;
The increment and decrement operators can be applied in prefix form (before the variable) or postfix form (after the variable) Expression Operation Value of Expression count++ add 1 old value ++count add 1 new value count-- subtract 1 old value --count subtract 1 new value • When used alone in a statement, prefix and postfix forms make no difference • Have different effect in larger expressions
3 + x 3 + x++ then x++ a. b. Figure 2.16 Expression a) and equivalent expression b)
++x 3 + ++x then 3 + x a. b. Figure 2.17 Expression a) and equivalent expression b)
Assignment Operators • Often we perform an operation on a variable, then store the result back into that variable • Java provides assignment operators to simplifies the notations Operator Example Equivalent To += x += y x = x + y -= x -= y x = x - y *= x *= y x = x * y /= x /= y x = x / y %= x %= y x = x % y
Parameters • A method may have a list of (formal) parameters • Another method calls it by providing a matching list of arguments (or actual parameters) • Argument-parameter matching is the primary mechanism for the calling method to pass data to the called method • Java always passed arguments by value, meaning that the called method receives the values of the arguments • Changing value of a parameter has no effect on the correspond argument
Arguments 2, 2, 1 v.enterMoney Return Value 75 Figure 2.19 TheenterMoney “machine”
v :Vending2 v :Vending2 quarters = 20 dimes = 20 nickels = 20 candy = 10 quarters = 22 dimes = 22 nickels = 21 candy = 10 enterMoney selectCandy test enterMoney selectCandy test before after Figure 2.20 The state change from enterMoney
Before the call to cube(x) main During the call After the call x 12 12 12 0 0 1728 value cube 12 then 17 aNumber result 1728 Figure 2.21 Memory usage
Message and Input Dialogs • Output can be displayed in a popup message dialog rather than a console window JOptionPane.showMessageDialog(null, “hi there”); • The JOptionPane class is in javax.swing import javax.swing.JOptionPane; • The showInputDialog method of JOptionPane pops up a window that accepts input from the user String s =JOptionPane.showInputDialog (“How many quarters deposited? “); int q = Integer.parseInt(s);
Javax.swing default <<imports>> JOptionPane TestVending2 //other classes in //the same //directory <<imports>> vend Vending1 Figure 2.23 Package diagram
Colors and Coordinate Systems • A picture to be displayed is broken down into pixels, and each pixel is stored separately • Each pixel can be identified using a two-dimensional coordinate system • In Java, each pixel can be represented by three numbers between 0 and 225, the RGB value, that specify the intensity of the three primary colors • When referring to a pixel in a Java program, we use a coordinate system with the origin in the upper left corner
x y (0,0) (399,0) (0,299) (399,299) Figure 2.26 Coordinates, in pixels, for 400 by 300 window
Applets runs on a browser or applet viewer • Any applet always extends the Applet class • The Applet class provides a standard interface between the applets and their environment • We override the paint method of the Applet class to handle the paint events • A Graphics object can be used to write strings or draw pictures • An applet is part of a web page <applet code=“HelloApplet” width=400 height=300> </applet>