Download presentation
Presentation is loading. Please wait.
1
6/4/01 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
2
6/4/01 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
3
6/4/01 2.1 Names Objects can communicate by calling each other’s responsibilities by names Names of objects, their data and responsibilities are called identifiers ::= { | digit} ::= a..z | A..Z | _ | $ ::= 0..9 Keywords are reserved identifiers for special uses
4
6/4/01 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
5
6/4/01 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
6
6/4/01
7
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 */
8
6/4/01 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
9
6/4/01 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
10
6/4/01 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
11
6/4/01 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
12
6/4/01 Consider the statement: quarters = quarters + numberOfQuarters ;
13
6/4/01 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
14
6/4/01 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
15
6/4/01 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.
16
6/4/01 Figure 2.6 A Vending1 instance ___________:Vending1 quarters = 10 candyBars = 15 enterMoney selectMoney
17
6/4/01 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 )
18
6/4/01 Figure 2.7 A reference variable of type Vending1 ___________:Vending1 quarters = 10 candyBars = 15 enterMoney selectMoney byTheDoor
19
6/4/01 null machineA Figure 2.8 A null reference
20
6/4/01 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
21
6/4/01 Figure 2.9 After executing byTheDoor.enterMoney(3) ___________:Vending1 quarters = 13 candyBars = 15 enterMoney selectMoney byTheDoor
22
6/4/01 Figure 2.10 After executing byTheDoor.selectCandy() ___________:Vending1 quarters = 13 candyBars = 14 enterMoney selectMoney byTheDoor
23
6/4/01 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
24
6/4/01 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.
25
6/4/01 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
26
6/4/01 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
27
6/4/01 3 + 4 * 5 Figure 2.14 Multiplication gets its operands first
28
6/4/01 * 5 (3 + 4) Figure 2.15 Compute within parentheses first
29
6/4/01 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;
30
6/4/01 The increment and decrement operators can be applied in prefix form (before the variable) or postfix form (after the variable) ExpressionOperationValue of Expression count++ add 1 old value ++count add 1 new value count--subtract 1 old value --countsubtract 1 new value When used alone in a statement, prefix and postfix forms make no difference Have different effect in larger expressions
31
6/4/01 Figure 2.16 Expression a) and equivalent expression b) then 3 + x x++ a.b. 3 + x++
32
6/4/01 Figure 2.17 Expression a) and equivalent expression b) then ++x 3 + x a.b. 3 + ++x
33
6/4/01 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 OperatorExampleEquivalent 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
34
6/4/01 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
35
6/4/01 v.enterMoney Figure 2.19 The enterMoney “machine” Arguments Return Value 2, 2, 1 75
36
6/4/01 v :Vending2 quarters = 20 dimes = 20 nickels = 20 candy = 10 enterMoney selectCandy test before v :Vending2 quarters = 22 dimes = 22 nickels = 21 candy = 10 enterMoney selectCandy test after Figure 2.20 The state change from enterMoney
37
6/4/01 Figure 2.21 Memory usage cube aNumber 12 x value 0 After the call 12 17280 12 then 17 During the call 12 1728 main result Before the call to cube(x)
38
6/4/01 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);
39
6/4/01 Figure 2.23 Package diagram default TestVending2 //other classes in //the same //directory Javax.swing JOptionPane > vend Vending1 >
40
6/4/01 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
41
6/4/01 Figure 2.26 Coordinates, in pixels, for 400 by 300 window x (0,0) (0,299) (399,0) (399,299) y
42
6/4/01 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.