Presentation is loading. Please wait.

Presentation is loading. Please wait.

Five-Minute Review What steps do we distinguish in solving a problem by computer? What are essential properties of an algorithm? What is a definition of.

Similar presentations


Presentation on theme: "Five-Minute Review What steps do we distinguish in solving a problem by computer? What are essential properties of an algorithm? What is a definition of."— Presentation transcript:

1 Five-Minute Review What steps do we distinguish in solving a problem by computer? What are essential properties of an algorithm? What is a definition of Software Engineering? What types of programming error do we distinguish? What is the difference between compilation and interpretation? 1. Algorithmic design, 2. Coding 1. Clearly and unambiguously defined, 2. Effective, 3. Finite Discipline of writing programs so that they can be understood and maintained by others Syntax Errors, Bugs Compilation translates whole program into machine code before execution. Interpreter interprets program (in e.g. byte code) at run time.

2 Programming – Lecture 2 Programming by example (Chapter 2) Hello world
Patterns Classes, objects Graphical programming

3 Chapter 2—Programming by Example
The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java C H A P T E R 2 Programming by Example Example is always more efficacious than precept. —Samuel Johnson, Rasselas, 1759  2.1 The “Hello world” program 2.2 Perspectives on the programming process 2.3 A program to add two numbers 2.4 Programming idioms and patterns 2.5 Classes and objects 2.6 Graphical programs Chapter 2—Programming by Example

4 In C, the program to print “hello, world” is
1.1 Getting Started The only way to learn a new programming language is to write programs in it. The first program to write is the same for all languages: Print the words hello, world This is the big hurdle; to leap over it you have to be able to create the program text somewhere, compile it, load it, run it, and find out where your output went. With these mechanical details mastered, everything else is comparatively easy. In C, the program to print “hello, world” is #include <stdio.h> main() { printf("hello, world"); }

5 The “Hello World” Program in Java
A Java method consists of a series of statements. Here, the only statement is a call to add, which adds an object to the display. A class definition in Java typically contains a series of entries. This example has one entry, which is a method called run. The object to be added is indicated by supplying an argument to the add method. Here, the argument is a new GLabel object. In Java, objects are created by using a constructor, which consists of the keyword new followed by the class name and arguments. The next slide simulates the operation of HelloProgram so that you can get a sense of what appears on the display. The arguments supply information that the constructor needs to make the object, such as the string to display and the coordinates. The last few lines in the file define the HelloProgram class, which the extends keyword identifies as a GraphicsProgram. The next two lines are the imports, which indicate what library packages the program uses. This first few lines (everything between /* and */) are an example of a comment, which is intended for human readers. The simple “Hello World” example illustrates several features that are common to the programs you will see in this book. /* * File: HelloProgram.java * * This program displays "hello, world" on the screen. * It is inspired by the first program in Brian * Kernighan and Dennis Ritchie's classic book, * The C Programming Language. */ import acm.graphics.*; import acm.program.*; public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel( "hello, world", 100, 75 ) ); } /* * File: HelloProgram.java * * This program displays "hello, world" on the screen. * It is inspired by the first program in Brian * Kernighan and Dennis Ritchie's classic book, * The C Programming Language. */ import acm.graphics.*; import acm.program.*; public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel( "hello, world", 100, 75 ) ); } /* * File: HelloProgram.java * * This program displays "hello, world" on the screen. * It is inspired by the first program in Brian * Kernighan and Dennis Ritchie's classic book, * The C Programming Language. */ Java method is series of statements (add) import acm.graphics.*; import acm.program.*; public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel( "hello, world", 100, 75 ) ); }

6 Hello World – "Standard Java"
public class HelloWorld { public static void main (String[] args) { System.out.println("Hello World!"); } static methods in Java can be called without creating an object of class. Non-static methods are instance methods. System class is final and all of it’s members and methods are static so that we can’t subclass and override it’s behavior through inheritance. System class doesn’t provide any public constructors, so we can’t instantiate this class (for argument sake, we can instantiate it using Java Reflection) and that’s why all of it’s methods are static.

7 Hello World – "Standard Java"
public class HelloWorld { public static void main (String[] args) { System.out.println("Hello World!"); } static methods in Java can be called without creating an object of class. Non-static methods are instance methods. System class is final and all of it’s members and methods are static so that we can’t subclass and override it’s behavior through inheritance. System class doesn’t provide any public constructors, so we can’t instantiate this class (for argument sake, we can instantiate it using Java Reflection) and that’s why all of it’s methods are static.

8 Hello World – "ACM Java" import acm.program.*;
public class HelloWorld extends ConsoleProgram { public void run() { println("Hello World!"); }

9 Rationale for ACM Java We use ACM Java for didactic purposes
Programs are treated as objects, no static main method Easy to switch console/graphical programs Historic baggage from C is hidden Examples are compatible with text book For further details, see the home page of the ACM Java Task Force:

10 Hello World import acm.program.*;
public class HelloWorld extends ConsoleProgram { public void run() { println("Hello World!"); }

11 public class HelloProgram extends GraphicsProgram {
import acm.graphics.*; import acm.program.*; public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel("hello, world", 100, 75) ); } import acm.graphics.*; import acm.program.*; public class HelloProgram extends GraphicsProgram { public void run() { add( new GLabel("hello, world", 100, 75) ); } ACM: Association for Computing Machinery. It was founded in 1947 and is the world's largest[2] scientific and educational computing society. It is a not-for-profit professional membership group.[3] Its membership is more than 100,000 as of Its headquarters are in New York City. [Wikipedia] In Java, you need to have a method named main in at least one class. Standard hello world: public class HelloWorld { public static void main (String[] args) System.out.println("Hello World!"); } From An ACM console program, however, in most development environments (including Eclipse) does not need to have a "main" method specified. Instead, the code that should be executed in an ACM console program can be placed in a "run" method, as seen below. HelloProgram hello, world

12 Perspectives on the Programming Process
In his Pulitzer-prizewinning book, computer scientist Douglas Hofstadter identifies two concepts—holism and reductionism—that turn out to be important as you begin to learn about programming. Hofstadter explains these concepts in the form of a dialogue in the style of Lewis Carroll: I will be glad to indulge both of you, if you will first oblige me, by telling me the meaning of these strange expressions, “holism” and “reductionism”. Achilles: Crab: Holism is the most natural thing in the world to grasp. It’s simply the belief that “the whole is greater than the sum of its parts”. No one in his right mind could reject holism. Anteater: Reductionism is the most natural thing in the world to grasp. It’s simply the belief that “a whole can be understood completely if you understand its parts, and the nature of their ‘sum’”. No one in her left brain could reject reductionism.

13 A Program to Add Two Numbers
The next two statements read the input values from the user, each of which is a whole number, which is more formally called an integer. The input values are stored in memory cells called variables that serve as placeholders for those values. The next statement computes the sum by adding the values stored in the variables n1 and n2. In this statement, the + operator represents addition, as in standard mathematics. The final statement in the run method displays the result. In this statement, the + operator signifies concatenation, which consists of combining the operands together as strings. The next slide animates the operation of this program to illustrate the assignment of values to variables. The first statement in the program prints a message to the user describing what the program does. This program is an example of a ConsoleProgram, which reads input from the keyboard and displays characters on the screen. Such programs are not as exciting as graphical applications but are useful for illustrating programming concepts. As you saw in the case of the HelloProgram example, Java programs written using the acm.program package begin by executing the statements in the run method. The holistic perspective is particularly useful when you are first learning to program. When you look at a program, you should concentrate on understanding its operation in a general way rather than focusing on the details. Consider, for example, the following program, which adds two integers and prints their sum: import acm.program.*; public class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } import acm.program.*; public class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); }

14 Variables Name (Identifier) Type Value A box to put something into
int x = 42; A variable (with name) x of type int with initial value 42

15 Variables This program adds two numbers. 17 Enter n1: Enter n2: 25
class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } n1 n2 total 17 25 42 class Add2Integers extends ConsoleProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } Variables: - Name - Type - Value n1 n2 total 17 25 42 Add2Integers This program adds two numbers. 17 Enter n1: Enter n2: 25 The total is 42.

16 Programming Idioms and Patterns
Experienced programmers also often take a holistic approach to programming. Effective programmers can recognize a variety of common operations and have learned a standard solution strategy for each one. The code that implements such a solution strategy is called a programming idiom or programming pattern. Learning to use these patterns saves you from having to think about the nitty-gritty details. As an example, it is important to think of a statement like int n1 = readInt("Enter n1: "); not in terms of what each part of the statement means, but rather as a holistic pattern to read an integer from the user: int variable = readInt("prompt");

17 Java Packages Typically a collection of useful classes A.k.a. "library packages" or "libraries" import package.class;

18 Java Packages If several classes from same package are needed, may abbreviate: import package.*; Name of package may also include ".", but cannot use * to include several packages Advice: Use * sparingly Let the IDE Content Assist add import statements for you (Eclipse: Ctrl-Space)

19 Comments // A one-line comment // Another one-line comment /* * A longer comment. * Every program deserves a * comment – except for those * programs that only * live on slides. */

20 Programming Idioms / Patterns
Holistic vs. reductionistic Holistic pattern “read integer from user”: int variable = readInt("prompt");

21 Classes and Objects As described in the slides for Chapter 1, Java programs are written as collections of classes, which serve as templates for individual objects. Each object is an instance of a particular class, which can serve as a pattern for many different objects. Classes in Java form hierarchies. Except for the class named Object that stands at the top of the hierarchy, every class in Java is a subclass of some other class, which is called its superclass. A class can have many subclasses, but each class has only one superclass. A class represents a specialization of its superclass. If you create an object that is an instance of a class, that object is also an instance of all other classes in the hierarchy above it in the superclass chain. When you define a new class in Java, that class automatically inherits the behavior of its superclass.

22 Biological Models of Class Structure
The structure of Java’s class hierarchy resembles the biological classification scheme introduced by Scandinavian botanist Carl Linnaeus in the 18th century. Linnaeus’s contribution was to recognize that organisms fit into a hierarchical classification scheme in which the placement of individual species reflects anatomical similarities. Carl Linnaeus (1707–1778)

23 Biological Class Hierarchy
Living Things Plants Animals Fungi Kingdom Annelida Brachiopoda Arthropoda Mollusca Chordata Phylum Note that there can be many individual red ants, each of which is an instance of the same basic class. Crustacea Insecta Arachnida Order Hymenoptera Class Classification of the red ant Iridomyrmex purpureus Formicidae Family Every red ant is also an animal, an arthropod, and an insect, as well as the other superclasses in the chain. Iridomyrmex Genus purpureus Species

24 The acm.program Hierarchy
Applet JApplet Java class hierarchies are similar to the biological class hierarchy from the previous slide. This diagram, for example, shows the hierarchy formed by the classes in the acm.program package. Every ConsoleProgram is also a Program, a JApplet, and an Applet. That means that every ConsoleProgram can run as an applet on the web. The same is true for any DialogProgram or GraphicsProgram. Program ConsoleProgram DialogProgram GraphicsProgram class subclass extends superclass

25 The DialogProgram Class
public class Add2Integers extends DialogProgram { public void run() { println("This program adds two numbers."); int n1 = readInt("Enter n1: "); int n2 = readInt("Enter n2: "); int total = n1 + n2; println("The total is " + total + "."); } In object-oriented languages like Java, a class definition specifies the behavior of objects of that class. The DialogProgram class has exactly the same operations as the ConsoleProgram class; the only difference is that the input and output operations use popup dialogs instead of a console, as illustrated by the following implementation of AddTwoIntegers:

26 Graphical Programs The GraphicsProgram class makes it possible to create simple pictures on the screen. The conceptual model is that of a collage composed of objects on a canvas. Running a GraphicsProgram creates a window that serves as the background canvas for the collage. You create pictures by creating graphical objects of various kinds and then adding those objects to the canvas. In this chapter, you will learn how to work with labels, rectangles, ovals, and lines using the classes GLabel, GRect, GOval, and GLine. The complete set of graphics classes is introduced in Chapter 9.

27 Sending Messages to Objects
In many applications, you will need to change the appearance of a graphical object after you have created it. For example, you might want to have the object change its color or move to a new position on the canvas. In object-oriented languages like Java, such changes are the responsibility of the object. To change the color of an object you send a message to the object asking it to change color. where receiver is the object to which the message is directed, name identifies the type of message, and arguments is a list of values used to specify any other information associated with the message. receiver.name(arguments); Java uses the following syntax to send a message to an object:

28 Sending Messages to Objects
receiver.name(arguments); public class HelloProgram extends GraphicsProgram { public void run() { GLabel label = new GLabel("hello, world", 100, 75); label.setFont("SansSerif-36"); label.setColor(Color.RED); add(label); } label hello, world public class HelloProgram extends GraphicsProgram { public void run() { GLabel label = new GLabel("hello, world", 100, 75); label.setFont("SansSerif-36"); label.setColor(Color.RED); add(label); } The following program illustrates sending a message to an object. Note that the label doesn’t appear until it is added to the canvas. label hello, world hello, world hello, world HelloProgram hello, world skip simulation

29 The Java Coordinate System
Positions and distances in a graphics program are measured in terms of pixels, which are the individual dots that cover the screen. Unlike traditional mathematics, Java defines the origin of the coordinate system to be in the upper left corner. Values for the x coordinate increase as you move rightward across the screen; y coordinate values increase as you move downward. Creating a JLabel at a particular x and y position means that the baseline of the first character in the label appears at that point, as follows: HelloProgram Hello (100, 75)

30 The GObject Hierarchy GObject GRect GOval GLine GLabel
Operations on graphical objects are defined at each level of the hierarchy. Operations that apply to all graphical objects are specified at the GObject level, where they are inherited by each subclass. Operations that apply to a particular subclass are specified as part of the definition of that class. The GObject class represents the collection of all graphical objects. The four subclasses shown in this diagram correspond to particular types of objects: labels, rectangles, ovals, and lines. The class diagram makes it clear that any GLabel, GRect, GOval, or GLine is also a GObject.

31 Before you can appreciate the classes and methods available in acm
Before you can appreciate the classes and methods available in acm.graphics, you need to understand the assumptions, conventions, and metaphors on which the package is based. Collectively, these ideas that define the appropriate mental picture for a package are called a model. The model for a package allows you to answer various questions about how you should think about working in that domain. Before using a graphics package, for example, you need to be able to answer the following sorts of questions: • What are the real-world analogies and metaphors that underlie the package design? • How do you specify positions on the screen? • What units do you use to specify lengths? To support the notion of object-oriented design, the acm.graphics package uses the metaphor of a collage. A collage artist works by taking various objects and assembling them on a background canvas. Those objects might be geometrical shapes, words clipped from newspapers, lines formed from bits of string, or images taken from magazines. The acm.graphics package offers counterparts for all of these. The notion that the image is a collage has important implications for the way you describe the process of creating a design. If you are painting, you might talk about making a brush stroke in a particular position or filling an area with paint. In the collage model, the key operations are adding and removing objects, along with repositioning them on the background. Collages also have the property that some objects can be positioned on top of other objects, where they obscure whatever is behind them. Removing those objects reveals whatever used to be underneath. Wikipedia / marcel4995 / CC

32 Operations on the GObject Class
object.setColor(color) Sets color of object to specified color constant. object.setLocation(x, y) Changes location of object to point (x, y). object.move(dx, dy) Moves object on screen by adding dx and dy to its current coordinates. These operations apply to all GObjects Standard color names, defined in java.awt package: Color.BLACK Color.DARK_GRAY Color.GRAY Color.LIGHT_GRAY Color.WHITE Color.RED Color.YELLOW Color.GREEN Color.CYAN Color.BLUE Color.MAGENTA Color.ORANGE Color.PINK

33 Operations on the GLabel Class
Constructor new GLabel(text, x, y) Creates a label containing the specified text that begins at the point (x, y). Methods specific to GLabel class label.setFont( font) Sets the font used to display the label as specified by the font string. Font typically specified as string "family-style-size" where family denotes font family style is either PLAIN, BOLD, ITALIC, or BOLDITALIC size is integer indicating point size

34 Drawing Geometrical Objects
Constructors new GRect( x, y, width, height) Creates a rectangle whose upper left corner is at (x, y) of the specified size. new GOval( x, y, width, height) Creates an oval that fits inside the rectangle with the same dimensions. new GLine( x0, y0, x1, y1) Creates a line extending from (x0, y0) to (x1, y1). Methods shared by the GRect and GOval classes object.setFilled( fill) If fill is true, fills in the interior of the object; if false, shows only the outline. object.setFillColor( color) Sets the color used to fill the interior, which can be different from the border.

35 The GRectPlusGOval Program
public class GRectPlusGOval extends GraphicsProgram { public void run() { GRect rect = new GRect(100, 50, 125, 60); rect.setFilled(true); rect.setColor(Color.RED); add(rect); GOval oval = new GOval(100, 50, 125, 60); oval.setFilled(true); oval.setFillColor(Color.GREEN); add(oval); } oval rect public class GRectPlusGOval extends GraphicsProgram { public void run() { GRect rect = new GRect(100, 50, 125, 60); rect.setFilled(true); rect.setColor(Color.RED); add(rect); GOval oval = new GOval(100, 50, 125, 60); oval.setFilled(true); oval.setFillColor(Color.GREEN); add(oval); } rect oval GRectPlusGOval skip simulation

36 Summary Got started with “hello world” Holistic vs. reductionistic
Classes form hierarchy, subclass inherits from superclass Objects are instances of a class Java coordinates GObjects


Download ppt "Five-Minute Review What steps do we distinguish in solving a problem by computer? What are essential properties of an algorithm? What is a definition of."

Similar presentations


Ads by Google