Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 2 Java Programming Basics

Similar presentations


Presentation on theme: "Chapter 2 Java Programming Basics"— Presentation transcript:

1 Chapter 2 Java Programming Basics
11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

2 Introduction to Object-Oriented Programming with Java--Wu
Chapter 2 Chapter 2 Objectives After you have read and studied this chapter, you should be able to Identify the basic components of Java programs. Distinguish two types of Java programs-applications and applets. Write simple Java applications and applets. Describe the difference between object declaration and object creation. Describe the process of creating and running Java programs. Use MainWindow and MessageBox classes from the javabook package to write Java applications. Use the Graphics class from the standard Java package. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

3 The First Java Application
Chapter 2 The First Java Application A program to display a window on the screen. The size of the window is slightly smaller than the screen, and the window is positioned at the center of the screen with a default title Sample Java Application. The fundamental OOP concept illustrated by the program: An object-oriented program uses objects. The two most important concepts in object-oriented programming are the class and the object. In the broadest term, an object is a thing, both tangible and intangible, which we can imagine. A program written in object-oriented style will consist of interacting objects. For a program to maintain bank accounts for a bank, we may have many Account, Customer, Transaction, and ATM objects. An object is comprised of data and operations that manipulate these data. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

4 Program MyFirstApplication
Chapter 2 Program MyFirstApplication /* Program MyFirstApplication This program displays a window on the screen. The window is positioned at the center of the screen, and the size of the window is almost as big as the screen. */ import javabook.*; class MyFirstApplication { public static void main(String[ ] args) MainWindow mainWindow; mainWindow = new MainWindow(); mainWindow.setVisible( true ); } Notice how similar is this program to FunTime from Chapter 1. The structure of the two programs is exactly the same. The only difference is the objects used in the programs. One uses DoodleBoard, while the another uses MainWindow. The same program can be made to exhibit a starkingly different behavior simply by changing the objects used in the program. Declare a name Create an object Make it visible 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

5 Introduction to Object-Oriented Programming with Java--Wu
Points to Remember MainWindow mainWindow; class object (declare) mainWindow = new MainWindow(); new object from MainWindow class mainWindow.setVisible( true ); making it visible MainWindow – capitalization of class mainWindow – object No spaces CaSe SeNsiTiVe 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu

6 Object Diagram for MyFirstApplication
Chapter 2 Object Diagram for MyFirstApplication MainWindow mainWindow setVisible MyFirstApplication main true This diagram shows that the program includes a class named MyFirstApplication. This class has a method called main. The class sends a setVisible method with parameter true to a MainWindow object called mainWindow. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

7 Flow of the MyFirstApplication Program
MainWindow mainWindow; mainWindow = new MainWindow(); mainWindow.setVisible( true ); MainWindow mainWindow; mainWindow = new MainWindow(); mainWindow.setVisible( true ); mainWindow See page in text MainWindow State-of-Memory Diagram 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu

8 Introduction to Object-Oriented Programming with Java--Wu
Chapter 2 Object Declaration Class Name This class must be defined before this declaration can be stated. Object Name One object is declared here. MainWindow mainWindow; More Examples Account customer; Student jan, jim, jon; Vehicle car1, car2; To use an object in a program, we first declare and create an object, and then we send messages to it. The first step in using an object is to declare it. An object declaration designates the name of an object and the class to which the object belongs. Its syntax is <class name> <object names> ; where <object names> is a sequence of object names separated by commas and <class name> is the name of a class to which these objects belong. Any valid identifier that is not reserved for other uses can be used as an object name. An identifier is a sequence of letters and digits with the first one being a letter. We use an identifier to name a class, object, method, and others. Upper- and lowercase letters are distinguished. No spaces are allowed in an identifier. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

9 Introduction to Object-Oriented Programming with Java--Wu
Chapter 2 Object Creation Object Name Name of the object we are creating here. Class Name An instance of this class is created. Argument No arguments are used here. mainWindow = new MainWindow ( ) ; More Examples customer = new Customer( ); jon = new Student(“John Java” ); car1 = new Vehicle( ); An object declaration simply declares the name (identifier), which we use to refer to an object. The declaration does not create an object. To create the actual object, we invoke the new operation. The syntax for new is <object name> = new <class name> ( <arguments> ) ; where <object name> is the name of a declared object, <class name> is the name of the class to which the object belongs, and <arguments> is a sequence of values passed to the new operation. Notice the distinction between object declaration and object creation, as illustrated on Slide #6. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

10 Distinction Between Declaration and Creation
Chapter 2 Distinction Between Declaration and Creation Customer customer; customer = new Customer( ); Customer customer; customer = new Customer( ); customer = new Customer( ); customer Customer Customer Since there is no reference to the first Customer object when the second new statement, it will eventually be erased and returned to the system. Remember that when an object is created, a certain amount of memory space is allocated for storing this object. If this allocated but unused space is not returned to the system for other uses, the space gets wasted. This returning of space to the system is called deallocation, and the mechanism to deallocate unused space is called garbage collection. Created with the first new. Created with the second new. Reference to the first Customer object is lost. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

11 Introduction to Object-Oriented Programming with Java--Wu
Chapter 2 Sending a Message Object Name Name of the object to which we are sending a message. Method Name The name of the message we are sending. Argument The argument we are passing with the message. mainWindow setVisible ( true ) ; More Examples account.deposit( ); student.setName(“john”); car1.startEngine( ); Notice that the name of the message we send to an object or a class must be the same as the method’s name. Because they are the same, the message name is commonly omitted from the diagram as shown above. Because they are the same, the phrase “calling an object’s method” is synonymous to “sending a message to an object.” 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

12 Introduction to Object-Oriented Programming with Java--Wu
Chapter 2 Program Components A Java program is composed of comments, import statements, and class declarations. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

13 Program Component: Comment
Chapter 2 Program Component: Comment /* Program MyFirstApplication This program displays a window on the screen. The window is positioned at the center of the screen, and the size of the window is almost as big as the screen. */ import javabook.*; class MyFirstApplication { public static void main(String[ ] args) MainWindow mainWindow; mainWindow = new MainWindow(); mainWindow.setVisible( true ); } Comment A comment is any sequence of text that begins with the marker /* and terminates with another marker */. Another marker for a comment is double slashes //. This marker is used for a single-line comment. Any text between the double-slash marker and the end of a line is a comment. The third type of comment is called a javadoc comment. It is a specialized comment that can appear before the class declaration and other program elements yet to be described in the book. Javadoc comments begin with the /** marker and end with the */ marker. Although not required to run the program, comments are indispensable in writing easy-to- understand code. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

14 Matching Comment Markers
Chapter 2 Matching Comment Markers /* This is a comment on one line */ /* Comment number 1 */ Comment number 2 This is a comment Error: No matching beginning marker. These are part of the comment. The beginning and ending markers are matched in pairs; that is, every beginning marker must have a matching ending marker. A beginning marker is matched with the next ending marker that appears. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

15 Three Types of Comments
Chapter 2 Three Types of Comments /* This is a comment with three lines of text. */ Multiline Comment Single line Comments // This is a comment // This is another comment // This is a third comment /** * This class provides basic clock functions. In addition * to reading the current time and today’s date, you can * use this class for stopwatch functions. */ javadoc Comments The double slashes // marker is used for a single-line comment. Any text between the double-slash marker and the end of a line is a comment. The third type of comment is called a javadoc comment. It is a specialized comment that can appear before the class declaration and other program elements yet to be described in the book. Javadoc comments begin with the /** marker and end with the */ marker. One major benefit of using javadoc comments is the availability of a tool that generates a Web page automatically from the javadoc comments. Javadoc comments are the standard way of documenting Java programs. The asterisks on the second, third, and fourth lines are not necessary, but useful in marking the comments clearly. It is an accepted convention to place asterisks in this manner. Although not required, aligning the end marker as shown in the example is also an accepted convention. Information on javadoc and sample Web documentation pages that are generated from javadoc comments can be found at You can get a full documentation of the standard Java classes generated from javadoc comments at techdocs/api/ 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

16 Program Component: Import Statement
Chapter 2 Program Component: Import Statement /* Program MyFirstApplication This program displays a window on the screen. The window is positioned at the center of the screen, and the size of the window is almost as big as the screen. */ import javabook.*; class MyFirstApplication { public static void main(String[ ] args) MainWindow mainWindow; mainWindow = new MainWindow(); mainWindow.setVisible( true ); } Import Statement The import statement allows the program to use classes and their instances defined in the designated package. We develop object-oriented programs by using predefined classes whenever possible and defining our own classes when no suitable predefined classes are available. In Java, classes are grouped into packages. The Java compiler comes with many packages, and we supply one package called javabook with this textbook. We will explain the motivation behind using the javabook package in the next section. You can also put your own classes into a package so they can be used in other programs. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

17 Introduction to Object-Oriented Programming with Java--Wu
Use Comments to… Create a program header Explain blocks of code Comment on specific lines Help with debugging 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu

18 Import Statement Syntax and Semantics
Chapter 2 Import Statement Syntax and Semantics Package Name Name of the package that contains the classes we want to use. Class Name The name of the class we want to import. Use asterisks to import all classes. <package name> <class name> ; e.g javabook InputBox; More Examples import javabook.*; import java.awt.image.ColorModel; import com.drcaffeine.galapagos.*; To use the MainWindow class in the javabook package, we write javabook.MainWindow; which we read as “javabook dot MainWindow.” This notation is called dot notation. Notice that the import statement is terminated by a semicolon. If you need to import more than one class from the same package, then instead of using an import statement for every class, you can import them all using asterisk notation: <package name> . * ; 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

19 Program Component: Class Declaration
Chapter 2 Program Component: Class Declaration /* Program MyFirstApplication This program displays a window on the screen. The window is positioned at the center of the screen, and the size of the window is almost as big as the screen. */ import javabook.*; class MyFirstApplication { public static void main(String[ ] args) MainWindow mainWindow; mainWindow = new MainWindow(); mainWindow.setVisible( true ); } Class Declaration A Java program is composed of one or more classes, some of them are predefined classes, while others are defined by ourselves. In this sample program, there are two classes—MainWindow and MyFirstApplication. The MainWindow class is from the javabook package and the MyFirstApplication class is the class we define ourselves. To define a new class, we must declare it in the program. The word class is a reserved word used to mark the beginning of a class declaration. We can use any valid identifier to name the class. One of the classes in a program must be designated as the main class. The main class of the sample program is MyFirstApplication. In the designated main class, then we must define a method called main, because when a Java program is executed, the main method of a main class is executed first. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

20 Program Component: Method Declaration
Chapter 2 Program Component: Method Declaration /* Program MyFirstApplication This program displays a window on the screen. The window is positioned at the center of the screen, and the size of the window is almost as big as the screen. */ import javabook.*; class MyFirstApplication { public static void main(String[ ] args) MainWindow mainWindow; mainWindow = new MainWindow(); mainWindow.setVisible( true ); } Method Declaration 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

21 Method Declaration Elements
Chapter 2 Method Declaration Elements Modifier Return Type Method Name Parameter Method Body public static void main ( String[ ] args ) { MainWindow mainWindow; mainWindow = new MainWindow(); mainWindow.setVisible( true ); } The syntax for method declaration is <modifiers> <return type> <method name> ( <parameters> ) { <method body> } where <modifiers> is a sequence of terms designating different kinds of methods, <return type> is the type of data value returned by a method, <method name> is the name of a method, <parameters> is a sequence of values passed to a method, and <method body> is a sequence of instructions. We will explain the meanings of modifies, return types, and parameters in detail gradually as we progress through the book. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

22 Template for Simple Java Applications
Chapter 2 Template for Simple Java Applications center of the screen, and the size of the window is almost as big as the screen. */ import javabook.*; class MyFirstApplication { public static void main(String[ ] args) MainWindow mainWindow; mainWindow = new MainWindow(); mainWindow.setVisible( true ); } Comment Import Statements Class Name Comment: Use a comment to describe the program Import Statements: Include a sequence of import statements. Most of the early sample applications require only import javabook.*; Class Name: Give a descriptive name to the main class. Method Body: Include a sequence of instructions. Method Body 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

23 Steps in Executing Java Applications
Chapter 2 Steps in Executing Java Applications Step 1 Edit Type in the program using an editor and save the program to a file. Step 2 Compile Compile the source file. Step 3 Run Execute the compiled source file called bytecode file. A Java program consists of one main class and other classes. A source file is a file that contains a Java class. A Java compiler will generate a bytecode file from a source file if there are no errors in the source file. A Java interpreter will process the bytecode file and run the program. Step-by-step instructions can be found in the file Java Compiler How To.ppt. Click this image to read step-by-step instructions on how to edit, compile, and run Java programs. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

24 Introduction to Object-Oriented Programming with Java--Wu
Chapter 2 The javabook Package To become a good object-oriented programmer, one must first learn how to use predefined classes. We used predefined classes from the javabook package. To download the package or get its detailed documentation, please visit Dr. Caffeine's web site. Advantages of using javabook: Gives you a taste of how real-world programs are developed. Minimizes the impact of programming language syntax and semantics. Allows you to write practical programs without learning too many details. Serves as good example of how to design classes. Mr. Espresso: If I learn programming using javabook classes, will I be able to program only by using javabook classes? Will I still be able to program without using them? Dr. Caffeine: Keep in mind that javabook classes are not the only predefined classes we use in this book. You will learn many classes from the standard Java packages such as java.awt and java.io. By the time you finish Chapter 12, you can program with or without the javabook package. Another concern I have is what happens after I complete your course? Can I continue to use javabook? Yes, you are free to use the javabook classes. There are no restrictions on using them. You may use the javabook classes as is, or better yet, you can modify the classes to suit your needs. You can take javabook as the starting point of your own package. Source code for all the classes in the javabook package is available to you. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

25 Sample Program: Displaying Messages
Chapter 2 Sample Program: Displaying Messages Problem Statement Write an application that displays the message I Love Java. Design Alternative 1: Set the title of the MainWindow to the designated message. Alternative 2: Use a MessageBox object. This object is intended for displaying a single line of short text to grab the enduser’s attention. The MessageBox class is available from the javabook package. A MessageBox object is a special kind of window called a dialog box, or more simply, dialog. Every dialog box requires another kind of window called a frame as its owner. A MainWindow object is a frame window. We call a dialog box a subordinate of the owner frame. One characteristic of this relationship is that a subordinate dialog always appears in front of its owner frame. The owner-subordinate relationship is established when a dialog box is created by passing the owner frame window as an argument in new, as in messageBox = new MessageBox( mainWindow ); And we display the text by passing it as an argument in the show message to a Messagebox object: messageBox.show( "I Love Java" ); 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

26 Sample Program: Design Document
Design Document: DisplayMessage Class Purpose DisplayMessage The main class of theprogram. MainWindow The main frame window of the program. The title is set to Display Message. This class is from javabook. MessageBox The dialog for displaying the required message. This class is from javabook. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu

27 Sample Program: Object Diagram
MainWindow mainWindow setVisible DisplayMessage main true “I Love Java” MessageBox messageBox show 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu

28 Sample Program: Source Code
/* Program DisplayMessage The program displays the text "I Love Java". The program uses a MessageBox object from the javabook package to display the text. */ import javabook.*; class DisplayMessage { public static void main(String[] args) MainWindow mainWindow; //declare two objects MessageBox messageBox; //create two objects mainWindow = new MainWindow("Display Message"); messageBox = new MessageBox(mainWindow); mainWindow.setVisible( true ); //display two objects: first the frame messageBox.show("I Love Java"); //and then the dialog } 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu

29 Sample Program: Testing
Run the program, and you will see… 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu

30 Program MyFirstApplet
Chapter 2 Program MyFirstApplet /* Program MyFirstApplet An applet that displays the text "I Love Java" and a rectangle around the text. */ import java.applet.*; import java.awt.*; public class MyFirstApplet extends Applet { public void paint( Graphics graphic) graphic.drawString("I Love Java",70,70); graphic.drawRect(50,50,100,30); } Here’s the second type of Java program-an applet. This Java applet that displays the message I Love Java and draws a rectangle around the message. You should notice that this program has exactly the same program components as MyFirstApplication. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

31 Three Components of Program MyFirstApplet
Chapter 2 Three Components of Program MyFirstApplet /* Program MyFirstApplet An applet that displays the text "I Love Java" and a rectangle around the text. */ import java.applet.*; import java.awt.*; public class MyFirstApplet extends Applet { public void paint( Graphics graphic) graphic.drawString("I Love Java",70,70); graphic.drawRect(50,50,100,30); } Header Comment Import Statements This Java applet imports two packages: java.applet and java.awt. All applets will import the java.applet package as it contains the required superclass Applet. All applets that will draw graphics on the screen will import the java.awt package as it includes the Graphics class. Notice that the MyFirstApplet class does not have a main method. The main class for this program is the AppletViewer class as illustrated in the next slide. Class Declaration 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

32 Object Diagram for MyFirstApplet
Chapter 2 Object Diagram for MyFirstApplet AppletViewer main MyFirstApplet paint graphic The MyFirstApplet does not have a main method, because the AppletViewer class is the main class of the program. For applications, we define our own main class, but for applets, the AppletViewer class is set by default to be the main class of the program. For applets, we define a subclass of Applet that the AppletViewer uses when executed. A subclass of Applet is declared as public class <applet subclass> extends Applet { <class member declarations> } 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

33 Drawing Graphics inside the paint Method
Chapter 2 Drawing Graphics inside the paint Method public void paint( Graphics graphic) { graphic.drawString("I Love Java",70,70); graphic.drawRect(50,50,100,30); } Drawing This is where we draw on an applet window by using the Graphics methods. The AppletViewer class automatically sends the paint message with a Graphics object as an argument to an applet. We use Graphics objects to display text, lines, and other graphics. In this sample applet, we send two messages to the object graphic. The first message graphic.drawString("I Love Java", 70, 70); displays the text I Love Java at the specified position (70, 70). The second message graphic.drawRect(50, 50, 100, 30); displays a rectangle 100 pixels wide and 30 pixels high at the specified position (50, 50). 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

34 Introduction to Object-Oriented Programming with Java--Wu
Chapter 2 Drawing Methods drawLine( x1, y1, x2, y2) draws a line from (x1,y1) to (x2, y2) drawRect(x, y, w, h) draws a rectangle w pixels wide and h pixels high at (x,y). drawOval( x, y, w, h) draws an oval w pixels wide and h pixels high at (x, y). See java.awt.Graphics for information on these and other drawing methods. There are many drawing methods provided in the Graphics class and its newest companion class Graphics2D. Learning these methods are not directly relevant to learning OOP so we won’t get into these methods any further here, but if you want to develop programs dealing with graphics you need to study these classes in detail. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

35 Template for Simple Java Applets
Chapter 2 Template for Simple Java Applets /* Program MyFirstApplet An applet that displays the text "I Love Java" and a rectangle around the text. */ import java.applet.*; import java.awt.*; public class MyFirstApplet extends Applet { public void paint( Graphics graphic) graphic.drawString("I Love Java",70,70); graphic.drawRect(50,50,100,30); } Comment Import Statements Class Name Comment: Use a comment to describe the program Import Statements: The early sample applets require only to import java.applet and java.awt packages Class Name: Give a descriptive name to the subclass of Applet. Method Body of paint: Include a sequence of instructions. Method Body 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

36 Executing Java Applets
Chapter 2 Executing Java Applets Basic steps for Java applications apply for applets as well. The main difference is that you need to define an HTML file. A Web browser or the AppletViewer needs this HTML file to execute an applet. An HTML file for the sample applet looks like this: <HTML> <BODY> <APPLET CODE="MyFirstApplet.class" WIDTH=300 HEIGHT=190> </APPLET> </BODY> </HTML> A Web browser reads a formatted document called a Web document or Web page. A Web document written in HyperText Markup Language (HTML) is called an HTML document, and a file that contains an HTML document is an HTML file. We use the suffix .html to name an html file. HTML is the standard language used for writing Web documents and consists of text and formatting tags called markup elements that specify the format for headers, paragraphs, hyperlinks, and other components of a document. One of the markup elements specifies the execution of an applet, giving the name of an applet to be executed, the area in the browser in which the applet is executed, and so forth. We need an HTML file that refers to an applet's bytecode file to run the applet. We use the html file MyFirstApplet.html to run the MyFirstApplet applet. 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

37 Edit-Compile-Run Cycle for Applets
Chapter 2 Edit-Compile-Run Cycle for Applets MyFirstApplet.java (source file) MyFirstApplet.class (bytecode file) MyFirstApplet.html (HTML file) Editor Compiler AppletViewer 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

38 Introduction to Object-Oriented Programming with Java--Wu
Let’s Try One… Page 62-66 Place name, Unified ID, Exercise 1, and description in header Display your name and Unified ID instead of “I Love Java” When done, print the code, sign it, and turn it in 11/20/2018 Introduction to Object-Oriented Programming with Java--Wu


Download ppt "Chapter 2 Java Programming Basics"

Similar presentations


Ads by Google