Download presentation
Presentation is loading. Please wait.
Published byDwight Beasley Modified over 9 years ago
1
An Introduction to Software Development Using JAVA
This chapter gives a glimpse of how software development evolved from artisanship into a professional engineering discipline. At the same time, students will get familiar with Java development tools and run their first programs.
2
Objectives: Understand the software development process, tools, and priorities Understand compilers and interpreters Learn about Java Virtual Machine, bytecodes Learn to set up and run simple console applications, GUI applications, and applets in Java Learn basic facts about OOP Students with a penchant for history can find a lot of interesting historical data on programming languages and software methodologies on the Internet.
3
Software Today: A Google search for SOFTWARE results in over 6.4 billion hits. Computers run everything from power grids, water utilities, TV satellites, and telephone networks to cars and coffee makers. Try to envision our lives if all programs were suddenly wiped out. Also try to appreciate the total effort that was needed to develop this invisible universe. 6,460,000,000
4
Software Applications
Large business systems Databases Internet, , etc. Military Embedded systems Scientific research AI Word processing and other small business and personal productivity tools Graphics / arts / digital photography Games The idea of developing intelligent computers (AI, or artificial intelligence) came about as soon as (or perhaps before) the first computer. Over the years the expectations turned out to be too optimistic. Little progress to report so far.
5
Software Development 1950-1960's: Now: Emphasis on efficiency
fast algorithms small program size limited memory use Often cryptic code Not user-friendly Emphasis on programmer’s productivity team development reusability of code easier maintenance portability Better documented User-friendly The main premise of the current software development culture is that hardware keeps getting faster and cheaper, so efficiency is no longer an issue. As a result, the performance of some programs even on fast computers may be rather sluggish, and we are forced to upgrade our computers every couple of years. This arrangement is good for both hardware and software companies: new computers have room for new software, bigger and slower software calls for new computers. This disregard for efficiency and economy in commercial software may be partly intentional.
6
Programming Languages
C C++ C# Assembly languages LISP Scheme Java Logo Fortran Pascal Python Thousands of programming languages and dialects have been described; many evolved over the years, others have disappeared, some existed for years but recently gained new popularity (e.g., Perl, Python). Java was initially meant for embedded systems (like home appliances) and for “interactive TV” but has survived due to the Internet. Machine code is called “first generation”; assembly languages are second generation; “high-level languages” (Fortran, Basic, Pascal, Smalltalk, etc.) are third generation. Fourth generation — visual prototyping systems with automatic code generation — was a buzzword in the 1980s (in the field called CASE, Computer-Aided Software Engineering), but the promise never really materialized. Machine code Basic Smalltalk Smalltalk-80
7
Software Development Tools
Editor programmer writes source code Compiler translates the source into object code (instructions specific to a particular CPU) Linker converts one or several object modules into an executable program Debugger steps through the program “in slow motion” and helps find logical mistakes (“bugs”) A programming language has a strict syntax. A compiler parses the source code and checks the syntax. There are other programming tools. For example, version control software allows a team of programmers to keep track of changes to files, so that two programmers are not working with the same file at the same time.
8
The First “Bug” “(moth) in relay”
This is a neat legend, but actually the term “bug” was used earlier. Mark II Aiken Relay Calculator (Harvard University, 1945)
9
Compiled Languages: Edit-Compile-Link-Run
Editor Source code Compiler Object code Linker Executable program Editor Source code Compiler Object code If you read your code carefully and reason about it before compiling, the number of cycles through Edit-Compile-Link-Run will be reduced, perhaps even to one! Editor Source code Compiler Object code
10
Interpreted Languages: Edit-Run
Editor Source code Interpreter When you use an interpreted language, the program that is being executed is the interpreter; the text of your program serves as data for the interpreter.
11
Compiler vs. Interpreter
checks syntax generates machine-code instructions not needed to run the executable program the executable runs faster Interpreter: checks syntax executes appropriate instructions while interpreting the program statements must remain installed while the program is interpreted the interpreted program is slower A Java interpreter is built into a Java-enabled browser for running applets. Due to a legal dispute between Sun and Microsoft, Internet Explorer does not have the latest version of Java built in, but Sun provides a Java “plug-in” for it.
12
Java’s Hybrid Approach: Compiler + Interpreter
A Java compiler converts Java source code into instructions for the Java Virtual Machine. These instructions, called bytecodes, are the same for any computer / operating system. A CPU-specific Java interpreter interprets bytecodes on a particular computer. Java Virtual Machine is an imaginary computer with a CPU instruction set that is “the least common denominator” for typical real CPUs.
13
Java’s Compiler + Interpreter
Editor Compiler : : 7 Hello.java Hello.class K There is also JIT (Just-In-Time) compiler technology where the program is interpreted and compiled at the same time. On subsequent runs the compiled code is used; there is no need to reinterpret it. Interpreter Interpreter Hello, World!
14
Why Bytecodes? Platform-independent
Load from the Internet faster than source code Interpreter is faster and smaller than it would be for Java source Source code is not revealed to end users Interpreter performs additional security checks, screens out malicious code Java’s culture is pretty open, and many applets are available on the Internet with their source code. Still, software vendors may want to protect their source code. For obvious reasons, the interpreter wouldn’t allow an applet to read or write files on your computer. Hackers have peculiar ethics (or rather, a gap in ethics): they won’t go around checking locks on the doors of houses or cars or spread real disease germs (even if non-lethal ones), but they will break into your computer system (which may be much more harmful and expensive) and spread computer viruses.
15
JDK — Java Development Kit
javac Java compiler java Java interpreter appletviewer tests applets without a browser javadoc generates HTML documentation (“docs”) from source jar packs classes into jar files (packages) JDK lacks an editor, so we use non-JDK software to create the source code. Our main tools are javac, java, and appletviewer. IDE usually has a more convenient debugger than JDK’s debugger. We recommend not using a debugger at all while learning how to program. All these are command-line tools, no GUI
16
JDK (cont’d) Available free from Sun Microsystems
All documentation is online: Many additional Java resources on the Internet It may be better to download Java docs together with the JDK and install them on the school server.
17
Java IDE GUI front end for JDK
Integrates editor, javac, java, appletviewer, debugger, other tools: specialized Java editor with syntax highlighting, autoindent, tab setting, etc. clicking on a compiler error message takes you to the offending source code line Usually JDK is installed separately and an IDE is installed on top of it. Most Java IDEs are written in Java. JCreator is an exception: it is written in C++ and is a little more compact and faster. It requires that JDK be installed. Install the JDK first, before the IDE.
18
Types of Programs Console applications GUI applications Applets
Console applications emulate a teletype device; they are sometimes called terminal applications (comes from old text-only terminals). Applets
19
Console Applications Simple text dialog:
prompt input, prompt input ... result C:\javamethods\Ch02> path=%PATH%;C:\Program Files\Java\jdk 1.5.0_07\bin C:\javamethods\Ch02> javac Greetings2.java C:\javamethods\Ch02> java Greetings2 Enter your first name: Josephine Enter your last name: Jaworski Hello, Josephine Jaworski Press any key to continue... Console applications may be not much fun, but they do the job when you need to test a simple calculation or algorithm. The path=... command tells the system where to look for java.exe and javac.exe.
20
Command-Line Arguments
C:\javamethods\Ch02> javac Greetings.java C:\javamethods\Ch02> java Greetings Josephine Jaworski Hello, Josephine Jaworski Command-line arguments are passed to main as an array of Strings. public class Greetings { public static void main(String[ ] args) String firstName = args[ 0 ]; String lastName = args[ 1 ]; System.out.println("Hello, " + firstName + " " + lastName); } Command-line arguments are not specific to Java: C and C++ have them, as well as other languages under Unix, MS-DOS, etc. In Windows, use the Command Prompt application. The Java source file name is a command-line argument for javac. Likewise, the HTML file name is a command-line argument for appletviewer.
21
Command-Line Args (cont’d)
Can be used in GUI applications, too IDEs provide ways to set them (or prompt for them) An IDE usually provides a way to set command-line args (on a Mac, too) or prompts for them when you run your program. Josephine Jaworski
22
Greetings2.java import java.util.Scanner; public class Greetings2 {
public static void main(String[ ] args) Scanner kboard = new Scanner(System.in); System.out.print("Enter your first name: "); String firstName = kboard.nextLine( ); System.out.print("Enter your last name: "); String lastName = kboard.nextLine( ); System.out.println("Hello, " + firstName + " " + lastName); System.out.println("Welcome to Java!"); } Prompts The Scanner class has been added to the java.util package in Java It simplifies reading numbers, words, and lines of text from the keyboard and files.
23
GUI Applications Menus Clickable panel Buttons Slider
This screen is from the Marine Biology Simulation case study, developed by Alyce Brady for the College Board and used on the AP CS exams for several years. Buttons Slider
24
HelloGui.java GUI libraries import java.awt.*; import javax.swing.*;
public class HelloGui extends JFrame { < ... other code > public static void main(String[ ] args) HelloGui window = new HelloGui( ); // Set this window's location and size: // upper-left corner at 300, 300; width 200, height 100 window.setBounds(300, 300, 200, 100); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } GUI libraries JFrame is a Swing library class for a generic program window. In a GUI program the program itself defines the initial dimensions of the program window. In an applet, the dimensions are defined in the <applet> tag in the HTML file.
25
HelloApplet.java import java.awt.*; import javax.swing.*;
public class HelloApplet extends JApplet { public void init( ) ... } < ... other code > No main in applets: the init method is called by JDK’s appletviewer or the browser Like JFrame, JApplet is also a Swing library class — but for an applet. We redefine its init method.
26
OOP — Object-Oriented Programming
An OOP program models a world of active objects. An object may have its own “memory,” which may contain other objects. An object has a set of methods that can process messages of certain types. “Methods” in Java are like functions in C or C++. Calling an object’s method is often phrased as “sending a message” to the object.
27
OOP (cont’d) A method can change the object’s state, send messages to other objects, and create new objects. An object belongs to a particular class, and the functionality of each object is determined by its class. A programmer creates an OOP application by defining classes. For example, a program may have a class Robot and an object of that class. A Robot object keeps in its memory its initial and current position. A robot has methods to step forward and to turn. Another class may be Position; the initial and current positions may be objects of that class. Robot’s method “forward” may call Position’s method “move.” The number of classes in a project may be quite large, but they are usually short. In Java each class is stored in a separate file. (An exception are the so-called inner classes that are embedded inside another class. They are not discussed in this book.) The name of the file must be exactly the same as the name of the class (including upper and lower case) with the extension .java.
28
The Main OOP Concepts: Inheritance: a subclass extends a superclass; the objects of a subclass inherit features of the superclass and can redefine them or add new features. Event-driven programs: the program simulates asynchronous handling of events; methods are called automatically in response to events. Event-driven applications are necessitated by GUI: the program cannot predict which button or menu the user will click next; it reacts to different events as they come. The robot program may have a “Step” button, for instance. Inheritance allows you to reuse most of the code in a class and redefine or add a couple of things. We could extend Robot into a JumpingRobot, adding a method jump. These concepts will become clearer in the next chapter and in the subsequent chapters.
29
Inheritance A programmer can define hierarchies of classes
More general classes are closer to the top Person Child Adult We say that a Child IS-A (kind of) Person; a Toddler IS-A (kind of) Child. Each subclass inherits all the methods of its superclass, and may redefine some of them and/or add new methods. Baby Toddler Teen
30
OOP Benefits Facilitates team development
Easier to reuse software components and write reusable software Easier GUI (Graphical User Interface) and multimedia programming At least these are the claims. OOP is definitely good for GUI development. But is it universally applicable in any type of project? OOP originated in academia; in a rather unique situation, businesses have spent millions of dollars converting to OOP and retraining their programmers without serious formal cost-benefit analysis. Prior to OOP the big thing was structured programming and top-down development.
31
Review: What are some of the current software development concerns?
What are editor, compiler, debugger used for? How is a compiler different from an interpreter? Name some of the benefits of Java’s compiler+interpreter approach. Define IDE. What are some of the current software development concerns? Team development, reusability, easier maintenance, portability, user-friendliness. What are editor, compiler, debugger used for? Creating source code (program’s text); compiling source into object code (CPU instructions); running a program in a controlled manner and correcting bugs, respectively. How is a compiler different from an interpreter? A compiler creates object modules that can be linked into an executable. The compiler is not needed to run the executable. An interpreter interprets the source and executes appropriate instructions. It must be installed and active to execute program statements. Name some benefits of Java’s compiler + interpreter approach. Bytecodes are device-independent, load faster, allow for security checks, and don’t reveal source code. Define IDE. Integrated Development Environment — combines software development tools under one GUI.
32
Review (cont’d): What is a console application?
What are command-line arguments? What is a GUI application? What is the difference between a GUI application and an applet? What is OOP? Define inheritance. What is a console application? An application in the style of the old teletype or terminal (console): uses a dialog with text prompts and user input. What are command-line arguments? An array of strings passed to the program from the operating system command line that runs the program (or from a special option box in an IDE). What is a GUI application? An application with a graphical user interface, often used with a mouse or another pointing device. What is the difference between a GUI application and an applet? An application runs on the computer where it is installed. An applet is embedded in a web page and is usually downloaded from the Internet (or a local network) together with the HTML document. What is OOP? Object-Oriented Programming — a program simulates a world of active objects. Define inheritance. Inheritance is a way to derive a class (a subclass) from another class (the superclass), adding new features and/or redefining some of the features.
33
Introduction Present the syntax of Java Introduce the Java API
Demonstrate how to build stand-alone Java programs Java applets, which run within browsers e.g. Netscape Example programs
34
Why Java? It’s the current “hot” language
It’s entirely object-oriented It has a vast library of predefined objects and operations It’s more platform independent this makes it great for Web programming It’s more secure It isn’t C++
35
Applets, Servlets and Applications
An applet is designed to be embedded in a Web page, and run by a browser Applets run in a sandbox with numerous restrictions; for example, they can’t read files and then use the network A servlet is designed to be run by a web server An application is a conventional program
36
Building Standalone JAVA Programs (on UNIX)
Prepare the file foo.java using an editor Invoke the compiler: javac foo.java This creates foo.class Run the java interpreter: java foo
37
Java Virtual Machine The .class files generated by the compiler are not executable binaries so Java combines compilation and interpretation Instead, they contain “byte-codes” to be executed by the Java Virtual Machine other languages have done this, e.g. UCSD Pascal This approach provides platform independence, and greater security
38
HelloWorld (standalone)
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } Note that String is built in println is a member function for the System.out class
39
Comments are almost like C++
/* This kind of comment can span multiple lines */ // This kind is to the end of the line /** * This kind of comment is a special * ‘javadoc’ style comment */
40
Primitive data types are like C
Main data types are int, double, boolean, char Also have byte, short, long, float boolean has values true and false Declarations look like C, for example, double x, y; int count = 0;
41
Expressions are like C Assignment statements mostly look like those in C; you can use =, +=, *= etc. Arithmetic uses the familiar * / % Java also has ++ and -- Java has boolean operators && || ! Java has comparisons < <= == != >= > Java does not have pointers or pointer arithmetic
42
Control statements are like C
if (x < y) smaller = x; if (x < y){ smaller=x;sum += x;} else { smaller = y; sum += y; } while (x < y) { y = y - x; } do { y = y - x; } while (x < y) for (int i = 0; i < max; i++) sum += i; BUT: conditions must be boolean !
43
Control statements II switch (n + 1) { case 0: m = n - 1; break; case 1: m = n + 1; case 3: m = m * n; break; default: m = -n; break; } Java also introduces the try statement, about which more later
44
Java isn't C! In C, almost everything is in functions
In Java, almost everything is in classes There is often only one class per file There must be only one public class per file The file name must be the same as the name of that public class, but with a .java extension
45
Java program layout A typical Java file looks like:
import java.awt.*; import java.util.*; public class SomethingOrOther { // object definitions go here } This must be in a file named SomethingOrOther.java !
46
What is a class? Early languages had only arrays
all elements had to be of the same type Then languages introduced structures (called records, or structs) allowed different data types to be grouped Then Abstract Data Types (ADTs) became popular grouped operations along with the data
47
So, what is a class? A class consists of
a collection of fields, or variables, very much like the named fields of a struct all the operations (called methods) that can be performed on those fields can be instantiated A class describes objects and operations defined on those objects
48
Name conventions Java is case-sensitive; maxval, maxVal, and MaxVal are three different names Class names begin with a capital letter All other names begin with a lowercase letter Subsequent words are capitalized: theBigOne Underscores are not used in names These are very strong conventions!
49
The class hierarchy Classes are arranged in a hierarchy
The root, or topmost, class is Object Every class but Object has at least one superclass A class may have subclasses Each class inherits all the fields and methods of its (possibly numerous) superclasses
50
An example of a class class Person { String name; int age;
void birthday ( ) { age++; System.out.println (name + ' is now ' + age); } }
51
Another example of a class
class Driver extends Person { long driversLicenseNumber; Date expirationDate; }
52
Creating and using an object
Person john; john = new Person ( ); john.name = "John Smith"; john.age = 37; Person mary = new Person ( ); mary.name = "Mary Brown"; mary.age = 33; mary.birthday ( );
53
An array is an object Person mary = new Person ( );
int myArray[ ] = new int[5]; or: int myArray[ ] = {1, 4, 9, 16, 25}; String languages [ ] = {"Prolog", "Java"};
54
Objects and Classes The First Steps case study in this chapter is rich enough to illustrate the main OOP concepts and give students some material for fun exercises.
55
Objectives: See an example of a small program written in OOP style and discuss the types of objects used in it Learn about the general structure of a class, its fields, constructors, and methods Get a feel for how objects are created and how to call their methods Learn a little about inheritance in OOP This chapter gives an introduction to the main Java and OOP concepts but does not require their full understanding. In terms of grasping the big picture, each student proceeds at his or her own pace. The same concepts are covered later in more depth. Here students get a general idea of how things are put together, get a feel for OOP, and work on exercises that require rearranging small pieces of code.
56
OOP An OO program models the application as a world of interacting objects. An object can create other objects. An object can call another object’s (and its own) methods (that is, “send messages”). An object has data fields, which hold values that can change while the program is running. A role play exercise may help students grasp the notion of objects and methods.
57
Objects Can model real-world objects
Can represent GUI (Graphical User Interface) components Can represent software entities (events, files, images, etc.) Can represent abstract concepts (for example, rules of a game, a particular type of dance, etc.) In Java, numbers and characters are not objects but there are so-called wrapper classes Integer, Double, Character, etc., which represent numbers and characters as objects.
58
Classes and Objects A class is a piece of the program’s source code that describes a particular type of objects. OO programmers write class definitions. An object is called an instance of a class. A program can create and use more than one object (instance) of the same class. Creation of an object is called instantiation (of its class).
59
Class Object A blueprint for objects of a particular type
Defines the structure (number, types) of the attributes Defines available behaviors of its objects Attributes Behaviors For example, one of the behaviors of an object may be to compute something. All the objects of the class will use the same formula for the computation, but the result may depend on the specific values of object’s attributes at the time of the computation.
60
Class: Car Object: a car
Attributes: String model Color color int numPassengers double amountOfGas Behaviors: Add/remove a passenger Get the tank filled Report when out of gas Attributes: model = "Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5 Behaviors: The values of some attributes (e.g., model, color) remain constant. The values of other attributes (e.g., number of passengers, amount of gas) may change while the program is running. An object has a reference to the table of entry points for the methods of its class.
61
Class vs. Object A piece of the program’s source code
Written by a programmer An entity in a running program Created when the program is running (by the main method or a constructor or another method) When an object is created, a chunk of memory is allocated to hold its attributes. When the object is no longer used by any other object, its memory is returned to the free memory pool (a process known as “garbage collection”).
62
Class vs. Object Specifies the structure (the number and types) of its objects’ attributes — the same for all of its objects Specifies the possible behaviors of its objects Holds specific values of attributes; these values can change while the program is running Behaves appropriately when called upon The attributes are the same for all objects of the same class, but their values may be different.
63
Classes and Source Files
Each class is stored in a separate file The name of the file must be the same as the name of the class, with the extension .java public class Car { ... } Car.java By convention, the name of a class (and its source file) always starts with a capital letter. In the Unix operating system, where Java started, file names are case-sensitive. In Windows the names can use upper- and lowercase letters, but names that differ only in case are deemed the same. But javac and java still care. Note that in command-line use of JDK, javac takes a file name SomeThing.java, while java takes a class name SomeThing (no extension). We will talk more about stylistic conventions vs. the required Java syntax in Chapter 5. (In Java, all names are case-sensitive.)
64
Libraries Java programs are usually not written from scratch.
There are hundreds of library classes for all occasions. Library classes are organized into packages. For example: java.util — miscellaneous utility classes java.awt — windowing and graphics toolkit javax.swing — GUI development package Go to Java API docs and examine the list of packages in the upper-left corner. We will mostly use classes from java.lang, java.util, java.awt, java.awt.event, javax.swing, and java.io.
65
import Full library class names include the package name. For example:
java.awt.Color javax.swing.JButton import statements at the top of the source file let you refer to library classes by their short names: import javax.swing.JButton; ... JButton go = new JButton("Go"); A package name implies the location of the class files in the package. For example, java.awt.event implies that the classes are in the java/awt/event subfolder. In reality, packages are compressed into .jar files that have this path information for classes saved inside. A .jar file is like a .zip file; in fact, it can be opened with a program that normally reads and creates .zip files (for example, rename x.jar into x.zip). import is simply a substitution directive that says: Whenever you see JButton, treat it like javax.swing.JButton. No files are moved or included. If you want a parallel to C++, import is more like #define than #include. Fully-qualified name
66
import (cont’d) You can import names for all the classes in a package by using a wildcard .*: import java.awt.*; import java.awt.event.*; import javax.swing.*; java.lang is imported automatically into all classes; defines System, Math, Object, String, and other commonly used classes. Imports all classes from awt, awt.event, and swing packages Some programmers do not like .* and prefer to list all imported classes individually. Once the number of library classes used becomes large, this becomes too tedious. It is also harder to change the class: you need to add import statements for each library class added.
67
public class SomeClass
SomeClass.java import ... import statements public class SomeClass Class header { Attributes / variables that define the object’s state; can hold numbers, characters, strings, other objects Fields Constructors Methods Procedures for constructing a new object of this class and initializing its fields Some programming languages (Pascal, for example) distinguish between functions and procedures. A function performs a calculation and returns the resulting value. A procedure does something but does not return any value. In Java, a method that returns a value is like a function; a method that is declared void does not return any value, so it is like a procedure. A constructor is special procedure for constructing an object. It has no return value and it is not even declared void. Other than that, constructors are similar to methods. Actions that an object of this class can take (behaviors) }
68
public class Foot Fields Constructor Methods { private Image picture;
private CoordinateSystem coordinates; public Foot (int x, int y, Image pic) picture = pic; coordinates = new CoordinateSystem (x, y, pic); } public void moveForward (int distance) coordinates.shift (distance, 0); public void moveSideways (int distance) coordinates.shift (0, distance); ... Fields Constructor Methods The name of the constructor is the same as the name of the class, so it starts with a capital letter. The programmer gives names to fields and methods. Style: by convention, the names of methods and fields start with a lowercase letter. Names of fields should sound like nouns, and names of methods should sound like verbs.
69
Fields A.k.a. instance variables
Constitute “private memory” of an object Each field has a data type (int, double, String, Image, Foot, etc.) Each field has a name given by the programmer In Java, fields represent attributes of an object.
70
Fields (cont’d) private [static] [final] datatype name;
You name it! Fields (cont’d) private [static] [final] datatype name; Usually private int, double, etc., or an object: String, Image, Foot May be present: means the field is shared by all objects in the class May be present: means the field is a constant More on syntax for declaring fields in Chapter 6. Programmers strive to make their programs readable. One of the important tools in this struggle is to give meaningful names to classes, fields, variables, and methods: not too short, not too long, and descriptive. private Foot leftFoot;
71
Constructors Short procedures for creating objects of a class
Always have the same name as the class Initialize the object’s fields May take parameters A class may have several constructors that differ in the number and/or types of their parameters It is usually a good idea to provide a so-called “no-args” constructor that takes no parameters (arguments). If no constructors are supplied at all, then Java provides one default no-args constructor that only allocates memory for the object and initializes its fields to default values (numbers to zero, booleans to false, objects to null). A class may have only one no-args constructor. In general, two constructors for the same class with exactly the same number and types of parameters cannot coexist.
72
Constructors (cont’d)
The name of a constructor is always the same as the name of the class public class Foot { private Image picture; private CoordinateSystem coordinates; public Foot (int x, int y, Image pic) picture = pic; coordinates = new CoordinateSystem(x, y, pic); } ... A constructor can take parameters Fields that are not explicitly initialized get default values (zero for numbers, false for booleans, null for objects). Initializes fields
73
Constructors (cont’d)
// FootTest.java ... Image leftShoe = ...; Foot leftFoot = new Foot (5, 20, leftShoe); An object is created with the new operator The number, order, and types of parameters must match public class Foot { ... public Foot (int x, int y, Image pic) } If a class has several constructors, new can use any one of them. Constructor
74
Constructors (cont’d)
JButton’s constructors (from API docs). JButton has five constructors; when we created the “Go” button we used the fourth one: the one that takes a string as an argument and displays it on the button. JButton go = new JButton("Go");
75
Methods Call them for a particular object: leftFoot.moveForward(20);
amy.nextStep( ); ben.nextStep( ); go.setText("Stop"); When an object calls its own method, then the dot-prefix is not required.
76
Methods (cont’d) The number and types of parameters (a.k.a. arguments) passed to a method must match method’s parameters: public void drawString ( String msg, int x, int y ) { ... } Methods in different classes may have the same name. Two methods in the same class may have the same name, too, but then they must differ in the number or types of parameters. Then the compiler figures out which one to call. These are called “overloaded methods.” g.drawString ("Welcome", 120, 50);
77
Methods (cont’d) A method can return a value to the caller
The keyword void in the method’s header indicates that the method does not return any value public void moveSideways(int distance) { ... } A value is returned using the return statement.
78
Encapsulation and Information Hiding
A class interacts with other classes only through constructors and public methods Other classes do not need to know the mechanics (implementation details) of a class to use it effectively Encapsulation facilitates team work and program maintenance (making changes to the code) If a change in private fields or methods occurs, then only that class has to change; other classes are not affected.
79
Methods (cont’d) Constructors and methods can call other public and private methods of the same class. Constructors and methods can call only public methods of another class. Class X private field private method Class Y Public/private designations help to isolate programmers from each other: one programmer needs to know little about other programmers’ classes: only their public interface. Even if the same programmer writes two classes, they are isolated from each other. public method public method
80
Inheritance In OOP a programmer can create a new class by extending an existing class Superclass (Base class) subclass extends superclass Several classes can extend the same superclass, but a subclass can extend only one superclass (that is there is no multiple inheritance in Java). Subclass (Derived class)
81
A Subclass... inherits fields and methods of its superclass
can add new fields and methods can redefine (override) a method of the superclass must provide its own constructors, but calls superclass’s constructors does not have direct access to its superclass’s private fields Paradox: a subclass inherits private fields of its superclass but does not have direct access to them.
82
public class Pacer extends Walker {
public Pacer (int x, int y, Image leftPic, Image rightPic) super (x, y, leftPic, rightPic); } public void turnAround () Foot lf = getLeftFoot (); Foot rf = getRightFoot (); lf.turn (180); rf.turn (180); lf.moveSideways (-PIXELS_PER_INCH * 8); rf.moveSideways (PIXELS_PER_INCH * 8); Constructor Calls Walker’s constructor using super A new method Pacer extends Walker. We can say that a Pacer IS-A Walker. Here Pacer adds a new method but it does not redefine any of the Walker’s methods. Calls Walker’s accessor methods
83
public int distanceTraveled() return stepsCount * stepLength; }
public class Walker { ... public int distanceTraveled() return stepsCount * stepLength; } public class Slowpoke extends Walker { ... public int distanceTraveled() return super.distanceTraveled ( ) / 10; } Overrides Walker’s distanceTraveled method Slowpoke extends Walker. We can say that a Slowpoke IS-A Walker. Here Slowpoke redefines (overrides) Walker’s distanceTraveled method. Calls superclass’s distanceTraveled method
84
Objectives: Discuss primitive data types
Learn how to declare fields and local variables Learn about arithmetic operators, compound assignment operators, and increment / decrement operators Discuss common mistakes in arithmetic Also review the style: naming variables and using symbolic constants.
85
Variables A variable is a “named container” that holds a value.
q = q; means: 1. Read the current value of q 2. Subtract it from 100 3. Move the result back into q 5 count mov ax,q mov bx,100 sub bx,ax mov q,bx The code in the green box is 8086 assembly language for IBM PC; ax and bx are general-purpose registers; mov is the move instruction.
86
Variables (cont’d) Variables can be of different data types: int, char, double, boolean, etc. Variables can hold objects; then the type is the class of the object. The programmer gives names to variables. Names of variables usually start with a lowercase letter. More precisely, variables that represent objects hold references to (basically addresses of) objects. The space to hold the actual object is allocated elsewhere. Names of variables must be meaningful, not too long, not too short. If a name consists of several words, the subsequent words are capitalized. A name cannot start with a digit.
87
Variables (cont’d) A variable must be declared before it can be used:
int count; double x, y; JButton go; Walker amy; String firstName; Name(s) Type Several variables of the same type can be declared in the same statement, separated by commas. A declaration ends with a semicolon.
88
Variables (cont’d) The assignment operator = sets the variable’s value: count = 5; x = 0; go = new JButton("Go"); firstName = args[0]; The variable go’s value is the address of the memory location where this JButton object is stored. So assignment = is an action, not an equation. For example, count = count + 1; increments the value of the variable count.
89
Variables (cont’d) A variable can be initialized in its declaration:
int count = 5; JButton go = new JButton("Go"); String firstName = args[0]; In the same declaration, some variables may be initialized and others not.
90
Variables: Scope Each variable has a scope — the area in the source code where it is “visible.” If you use a variable outside its scope, the compiler reports a syntax error. Variables can have the same name when their scopes do not overlap. { int k = ...; ... } for (int k = ...) So scope is a compile-time concept, not a run-time concept. The compiler reports a syntax error, “Cannot resolve symbol.” If the scopes of two variables overlap, the variable defined in the inner scope takes precedence over the variable with the same name in the outer scope. It is easy to make a mistake and override a field with a local variable of the same name, as explained later.
91
Fields Fields are declared outside all constructors and methods.
Fields are usually grouped together, either at the top or at the bottom of the class. The scope of a field is the whole class. Local variables are for temporary use; they are created when you call a method and destroyed when you return from a method call. Fields have the lifetime of the object and are destroyed only when the object is destroyed.
92
Fields (cont’d) Or: public class SomeClass { Scope Fields }
Constructors and methods Or: public class SomeClass { } Regardless of where you place a field declaration, the field is “visible” in the whole class. The compiler scans the class’s code to locate and tabulate all the fields, then parses the code again and checks the syntax. A field’s value can be set in its declaration, in a constructor, or in one of the methods. Uninitialized fields get default values: 0 for numbers, null for objects (references), false for booleans (see Chapter 7). Constructors and methods Scope Fields
93
Local Variables Local variables are declared inside a constructor or a method. Local variables lose their values and are destroyed once the constructor or the method is exited. The scope of a local variable is from its declaration down to the closing brace of the block in which it is declared. If you create a temporary object in a method using new and then assign it to a local variable, then the object is destroyed automatically when the method is exited and its memory is released. Java has a “garbage collector" run-time mechanism to do that.
94
Local Variables (cont’d)
public class SomeClass { ... public SomeType SomeMethod (...) } Scope Local variable declared You can declare a local variable inside a for loop: for (int i = 0; i < 100; i++) The scope of such a variable is the body of the loop within braces, so it is undefined after the loop. Local variable declared
95
Variables (cont’d) Use local variables whenever appropriate; never use fields where local variables should be used. Give prominent names to fields, so that they are different from local variables. Use the same name for local variables that are used in similar ways in different methods (for example, x, y for coordinates, count for a counter, i, k for indices, etc.). Suppose several methods have a for loop and use k as a loop control variable. You may be tempted to make k a field to avoid declaring it in each method. Never do that! If you call one method from inside the loop in another method, you’ll get a nasty bug. It is good style to keep things that are needed locally local. But do give these variables the same name k to emphasize their similar roles in the program.
96
Variables (cont’d) Common mistakes: public void someMethod (...) {
int x = 0; ... int x = 5; // should be: x = 5; Worse, if the second declaration is inside a nested { } block: no syntax error is reported, but the outer variable is overridden in the block. As a novice, do not declare variables inside blocks. Variable declared twice within the same scope — syntax error
97
Variables (cont’d) Common mistakes: private double radius; ...
public Circle (...) // constructor { double radius = 5; Again, give fields prominent names and write the data type designator for a field only in the field’s declaration, never inside a constructor or method. Attention to detail is the key. Declares a local variable radius; the value of the field radius remains 0.0
98
Primitive Data Types int double char boolean byte short long float
Used in Java Methods A byte represents small numbers, from -127 to short uses two bytes to represent an integer from -215 to Java doesn’t have unsigned types.
99
Strings String is not a primitive data type
Strings work like any other objects, with two exceptions: Strings in double quotes are recognized as literal constants + and += concatenate strings (or a string and a number or an object, which is converted into a string) A literal string is an object; you can call its methods. "Catch " + 22 "Catch 22"
100
Literal Constants 'A', '+', '\n', '\t' -99, 2010, 0
new line tab 'A', '+', '\n', '\t' -99, 2010, 0 0.75, , 8., .5 “coin.gif", "1776", "y", "\n" char int \... are called “escape sequences” from the old printer terminology. '\\' represents a backslash character. 3.0 is better than 3. — more visible as a double. double String
101
Symbolic Constants Symbolic constants are initialized final variables:
private final int stepLength = 48; private static final int BUFFER_SIZE = 1024; public static final int PIXELS_PER_INCH = 6; In Java you can initialize a symbolic constant later, in a constructor.
102
Why Symbolic Constants?
Easy to change the value throughout the program, if necessary Easy to change into a variable More readable, self-documenting code Additional data type checking by the compiler But there is no need for symbolic constants like pubic final int ONE = 1;
103
Arithmetic Operators: +, -, /, * , %
The precedence of operators and parentheses is the same as in algebra m % n means the remainder when m is divided by n (for example, 17 % 5 is 2; 2 % 8 is 2) % has the same rank as / and * Same-rank binary operators are performed in order from left to right There is also the unary operator -, for example, sign = -sign; All unary operators have a higher rank than binary operators and are executed first.
104
Arithmetic (cont’d) The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions. If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int. If an expression has several binary operators of the same rank with no parentheses, the intermediate results are calculated from left to right. For example: x = a / b * c; is the same as temp = a / b; x = temp * c;
105
Arithmetic (cont’d) Caution: if a and b are ints, then a / b is truncated to an int… 17 / 5 gives 3 3 / 4 gives 0 …even if you assign the result to a double: double ratio = 2 / 3; This is another place to be very careful. Integer truncation can be useful. For example, find the whole number of weeks in a given number of days or the number of whole hours in a given number of minutes: int fullWeekCount = dayCount / 7; System.out.println(mins / 60 + " hours and " + mins % 60 + " minutes."); The double type of the result doesn’t help: ratio still gets the value 0.0.
106
Arithmetic (cont’d) To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3; double ratio = 2 / 3.0; int m = ..., n = ...; double factor = (double)m / (double)n; double factor = (double)m / n; double r2 = n / 2.0; Another reason for symbolic constants: if you declare a symbolic constant as a double, then casts to double are unnecessary and arithmetic errors are avoided. A few redundant casts are OK, and they make your code self-documenting. Casts
107
Arithmetic (cont’d) A cast to int can be useful: Returns a double
int ptsOnDie = (int)(Math.random() * 6) + 1; int miles = (int)(km * ); To round a negative double, subtract 0.5 before casting. Converts kilometers to miles, rounded to the nearest integer
108
Arithmetic (cont’d) Caution: the range for ints is from to (about -2·109 to 2·109) Overflow is not detected by the Java compiler or interpreter: n = ^n = n! = n = ^n = n! = n = ^n = n! = n = ^n = n! = n = ^n = n! = n = ^n = n! = n = ^n = n! = 109 is OK, but 1010 is already wrong. When you eventually overflow and hit the leftmost bit in an integer variable, the number becomes negative because this is the sign bit. 12 factorial is OK but 13 factorial is wrong, which is not immediately obvious if you don’t see the preceding factorial values. Java has a type long that uses eight bytes and can hold integer values from -263 to 263‑1.
109
Arithmetic (cont’d) Compound assignment operators: a = a + b; a += b;
Increment and decrement operators: a = a + 1; a++; a = a - 1; a--; a = a + b; gives away a novice. But so does a += a + b++; Do not use these in larger expressions
110
From Numbers to Strings
The easiest way to convert x into a string is to concatenate x with an empty string: String s = x + ""; The same rules apply to System.out.print(x) Empty string 'A' 123 -1 .1 3.14 Math.PI "A" "123" "-1" "0.1" "3.14" " " Concatenation occurs whenever at least one of the operands is a string. For example, System.out.println("1 + 2 = " ); displays 1 + 2 = 12;
111
From Objects to Strings
The toString method is called: public class Fraction { private int num, denom; ... public String toString () return num + "/" + denom; } It is a good idea to supply a reasonable toString method for your class. Fraction f = new Fraction (2, 3); System.out. println (f) ; f.toString() is called automatically Output: 2/3
112
Review: What is a variable?
What is the type of a variable that holds an object? What is meant by the scope of a variable? What is the scope of a field? What is the scope of a local variable? What is a variable? A named container that can hold a value. What is the type of a variable that holds an object? The class to which the object belongs. What is meant by the scope of a variable? The area in the source code where the variable is visible. What is the scope of a field? The whole class. What is the scope of a local variable? From its declaration down to the closing brace of the block in which it is declared.
113
Review (cont’d): Is it OK to give the same name to variables in different methods? Is it OK to give the same name to a field and to a local variable of the same class? What is the range for ints? When is a cast to double used? Is it OK to give the same name to variables in different methods? Yes, and moreover it is desirable if their roles are similar. Is it OK to give the same name to a field and to a local variable of the same class? Never. What is the range for ints? from -231 to When is a cast to double used? When the operands are ints but we want the correct result as a double. (Be sure to cast an individual operand, not the final result.)
114
Review (cont’d): Given what is the value of dC?
double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC? When is a cast to int used? Given double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC? 0 (5/9 gives 0 first, the rest doesn’t matter). When is a cast to int used? To truncate the double result of a calculation and store it in an int variable. Should compound assignment operators be avoided? On the contrary, they should be used, but not inside fancy expressions.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.