Download presentation
Presentation is loading. Please wait.
Published byNathaniel Johnson Modified over 7 years ago
1
Java Programming: Guided Learning with Early Objects
Chapter 3 Introduction to Objects and Classes
2
Objectives Learn about objects and reference variables
Explore how to use predefined methods in a program Become familiar with the class String Learn how to use the class Math Java Programming: Guided Learning with Early Objects
3
Objectives (continued)
Explore the wrapper classes Learn how to design your own classes Explore how to write your own methods Learn how to avoid bugs by preparing a class design document Java Programming: Guided Learning with Early Objects
4
Objectives (continued)
Learn how to do a walk-through of a class design Become familiar with the GUI components ContentPane, JFrame , JLabels , and JButtons Learn how to use the classes Color and Font Learn how to handle events in a program Java Programming: Guided Learning with Early Objects
5
Objects and Reference Variables
new operator System allocates memory space for specific data type Stores data in memory space Returns address of the memory space Reference variable stores address of memory location Object is an instance of a class Garbage collection: Java automatically reclaims unused memory Java Programming: Guided Learning with Early Objects
6
Figure 3-3 Variable str and object str
Java Programming: Guided Learning with Early Objects
7
Using Predefined Classes and Methods in a Program
Method: collection of programming statements to accomplish a task Java includes many predefined classes Predefined class includes predefined methods Organized as class libraries To use a predefined method, you must know: Name of the class and package Method name and parameters Java Programming: Guided Learning with Early Objects
8
The Dot Between the Class (Object) Name and the Class Member: A Precaution
Member access operator: dot operator (.) Dot separates reference variable from method Methods distinguished from variables by parentheses Methods with no parameters must have empty parentheses Java Programming: Guided Learning with Early Objects
9
The class String Index of first character in string is 0
Length of string: number of characters in it String variables are reference variables String object an instance of class String class String contains methods to process strings String variable invokes String method using the dot operator, method names, arguments Java Programming: Guided Learning with Early Objects
10
The class Math Method type is data type returned by the method
Contained in package java.lang Java Programming: Guided Learning with Early Objects
11
Using Methods of the class Math in a Program
Java does not require package java.lang to be imported Classes automatically imported by default static method: method heading contains the word static Non static method does not contain static Actual parameters: parameters used in a method call static import statements import static packagename.ClassName.* Java Programming: Guided Learning with Early Objects
12
Primitive Data Types and Wrapper Classes
Wrapper classes for primitive types: class Integer for int class Long for long class Double for double class Float for float class Character for char Wrapper classes are immutable Autoboxing and auto-unboxing simplify wrapping and unwrapping of primitives Java Programming: Guided Learning with Early Objects
13
The class Character (Optional)
Class Character manipulates characters Contained in package java.lang public static methods of class Character used like methods of class Math Java Programming: Guided Learning with Early Objects
14
Introduction to Methods
Two categories of user-defined methods: Value-returning methods Void methods To use a method in a program, you must know: Name of method Number, type, order of parameters Data type of value returned Code required to accomplish the task Formal parameter: declared in method header Actual parameter: listed in call to a method Java Programming: Guided Learning with Early Objects
15
Syntax: Method Method syntax: modifier(s) returnType methodName
(formal parameter list) { statement(s) } modifier(s): visibility of method returnType: type of value method returns methodName: Java identifier Java Programming: Guided Learning with Early Objects
16
Syntax: Formal Parameter List
Syntax of a formal parameter list: dataType identifier, dataType identifier, … Java Programming: Guided Learning with Early Objects
17
Method Call Method call syntax: methodName (actual parameter list);
Java Programming: Guided Learning with Early Objects
18
Syntax: Actual Parameter List
Actual parameter list syntax: expression or variable, expression or variable,… Call a method, use name together with parameters in parentheses Formal parameter list may be empty Parentheses still needed Actual parameter list is empty if formal parameter list is also empty Java Programming: Guided Learning with Early Objects
19
return Statement Value-returning methods use return statement to return a value Pass value back when method completes Syntax: return expr; expr is a variable, constant, or expression return is a reserved word Method immediately terminates and control goes back to caller after return statement Java Programming: Guided Learning with Early Objects
20
Value-Returning Method
Local variable: variable is local to a method Example: public static double square(double num) { return num * num; } Java Programming: Guided Learning with Early Objects
21
Void Method Value-returning method returns one value
May want to return no value or many values Void method returns no value: public static void printNum(double x) { System.out.print(x); } Java Programming: Guided Learning with Early Objects
22
Flow of (Method) Execution
Methods can appear in any order Method main executes first Other methods execute when called Method call transfers control to first statement in method body After method finishes, control passed back to caller After value-returning method executes, return value replaces method call statement in caller Java Programming: Guided Learning with Early Objects
23
Classes Class: a collection of components called members
Syntax for defining a class: modifier(s) class ClassName modifier(s) { classMembers } private: cannot be accessed directly outside the class public: can be accessed directly outside class Java Programming: Guided Learning with Early Objects
24
Classes (continued) Members accessed directly from outside the class should be public Members that should not be accessed directly should be private User should never be given direct access to data members Instance variables: variables declared without using the modifier static Non static methods of a class are instance methods Java Programming: Guided Learning with Early Objects
25
Constructors Constructor has same name as the class
Executes automatically when object is created Used to guarantee instance variables are initialized Two types of constructors: With parameters Without parameters (default constructor) Has no return type Class can have more than one, but must have same name, different parameters Java Programming: Guided Learning with Early Objects
26
Variable Declaration and Object Instantiation
Declaring a reference variable of class type does not allocate memory Syntax for new operator: new className(); new className(arg1, arg2, …,argN); Number of arguments and types match formal parameters If type of arguments does not match, Java tries to find the best match Java Programming: Guided Learning with Early Objects
27
Defining Methods and Constructors
Method definition: public void setCurrentTemp(int cTemp) { currentTemp = cTemp; } Constructor definitions: public Thermometer() { currentTemp = 0; public Thermometer (int cTemp) { Java Programming: Guided Learning with Early Objects
28
The Method toString Definition of method toString:
public String toString() { return “Current temp: “ + currentTemp; } Suppose myTemp is a Thermostat object System.out.println(myTemp) is: Current temperature: 40 When object reference parameter to print, println, printf, method toString called Java Programming: Guided Learning with Early Objects
29
The Definition of the class Thermometer
public class Thermometer { private int currentTemp; public Thermometer() { currentTemp = 0; } public Thermometer (int cTemp) { currentTemp = cTemp; public void setCurrentTemp (int cTemp) { … Java Programming: Guided Learning with Early Objects
30
Avoiding Bugs: Designing a Class and Documenting the Design
Good programmers determine how to solve a problem completely before writing code Design written in enough detail that another programmer with same skill can produce code Algorithm describes means for achieving objective Usually described using pseudocode Pseudocode resembles code without formal syntax Java Programming: Guided Learning with Early Objects
31
Debugging: Design Walk-Throughs
Code walk-throughs find and remove bugs Design walk-throughs follow same principle Bugs may creep in at design time Design should be prepared carefully before presented to someone else Do not shortchange the design phase Java Programming: Guided Learning with Early Objects
32
GUI JFrame, JLabel, Colors, Fonts, JButton, and Handling an Event (Optional)
Output dialog box an example of a graphical user interface (GUI) GUI components are placed in the content pane of the window Inner window area below title bar, inside border Clicking a button causes an event to occur Java system listens for events and reacts Java Programming: Guided Learning with Early Objects
33
Figure 3-9 Java GUI components
Java Programming: Guided Learning with Early Objects
34
Figure 3-10 GUI of Figure 3-8 after clicking the Color button
Java Programming: Guided Learning with Early Objects
35
Figure 3-11 GUI of Figure 3-8 after clicking the Font button
Java Programming: Guided Learning with Early Objects
36
Creating a Window GUI components are objects
Instances of a particular class Attributes associated with a window: Every window has a title Every window has width and height Java Programming: Guided Learning with Early Objects
37
JFrame class JFrame provides methods to control attributes of a window
Two ways to create a window: Declare an object of type JFrame Extend class JFrame Inheritance: new class derived from existing class Use the modifier extends Java Programming: Guided Learning with Early Objects
38
JFrame (continued) Subclass of superclass inherits all properties of the superclass All public members of superclass directly accessed by the subclass Set window height in pixels Pixel is smallest unit of space on the screen If window created by using a JFrame object, properties have to be specified If window created by extending JFrame, it inherits JFrame properties Java Programming: Guided Learning with Early Objects
39
Getting Access to the Content Pane
Content pane is the inner area of window Below title, inside border Method getContentPane allows access to window content pane Must declare reference variable of Container type to use getContentPane Container pane; pane = getContentPane(); class Container in package java.awt Java Programming: Guided Learning with Early Objects
40
Table 3-6 Commonly Used Methods of the class Container
Java Programming: Guided Learning with Early Objects
41
JLabel Labels are objects of class JLabel
Instantiate JLabel objects to create labels JLabel in package javax.swing Labels have the attributes title, width, height Java Programming: Guided Learning with Early Objects
42
class Color Text black by default
class Color contained in package java.awt Java uses RGB color scheme Create color by mixing red, green, blue hues Color redColor = new Color(255,0,0); class Color defines standard colors as constants Java Programming: Guided Learning with Early Objects
43
class Font Show text in different fonts with class Font
Contained in java.awt Constructor of class Font takes three arguments: String specifying font name int value specifying font style int value specifying font size Expressed in points Guaranteed fonts: Serif, SanSerif , Times New Roman , Monospaced , Dialog , DialogInput Java Programming: Guided Learning with Early Objects
44
JButton Creates a button private JButton colorB, fontB;
colorB = new JButton(“Color”); fontB = new JButton(“Font”); Modify GridLayout to accommodate two rows and two columns, then add components pane.setLayout(new GridLayout(2,2)); pane.add(colorB); pane.add(fontB); Java Programming: Guided Learning with Early Objects
45
Handling an Event Clicking a JButton generates an action event
Sends message to action listener Sending an event to a listener invokes a method with the event as the argument Invocation happens automatically Specify two items: Corresponding listener object Register the listener Method to be invoked when event is sent Java Programming: Guided Learning with Early Objects
46
Figure 3-15 Processing an action event
Java Programming: Guided Learning with Early Objects
47
Summary Reference variables store a memory location
Objects are instances of a class Use the new operator to instantiate an object Unused memory collected and freed using Java garbage collector Predefined classes organized as collections of packages called class libraries Package must be imported to be used Java Programming: Guided Learning with Early Objects
48
Summary (continued) All primitive data types have corresponding wrapper class Wrapping and unwrapping facilitated by autoboxing and auto-unboxing Two types of methods: Value-returning methods Void methods Two types of parameters: Actual parameters Formal parameters Java Programming: Guided Learning with Early Objects
49
Summary (continued) Encapsulation: combining data and operations
Class members: components of a class Data members are fields Non static class methods are instance methods Constructor executes when object created Algorithm describes means for achieving objective Described with pseudocode Java Programming: Guided Learning with Early Objects
50
Summary (continued) Design walk-throughs help prevent bugs
Same process as code walk-throughs Create GUIs with JFrame, JLabel, JButton Clicking a button generates an action event When event is generated, message is sent to action listener Action listener invokes a method to perform some action Java Programming: Guided Learning with Early Objects
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.