slide 1 introduction to programming instances and classes variables java virtual machine using...
TRANSCRIPT
Slide 1
Introduction to Programming
Instances and Classes
Variables
Java Virtual Machine
Using Eclipse
Introduction toObject-Oriented
Programming
Lesson 01:Introduction
Slide 2
Text book:
Objects First with BlueJ297
Slides that reference the text book will have this
indicator
Slide 3
Introductionto Programming
Slide 4
Programming Language Different programming languages are different
ways (encodings) that turn into (same/similar) commands for the computer
Some early definitions (1)
Slide 5
Program A description in a programming language of a process that
achieves some result.
Algorithm A description of a process in a step-by-step manner.
The same algorithm could be written in many languages.
Procedure Instructions or recipes, a set of commands that show how
to prepare or make something.
Algorithms often implemented in one or more procedures.
Some early definitions (2)
Slide 6
Aspects of a computer program that must be designed:
The logical flow of the instructions
The mathematical procedures
The layout of the programming statements
The appearance of the output
The way information is presented to the user
The program’s “user friendliness”
Manuals, help systems, and/or other forms of written documentation.
The Art of Programming (1)
Slide 7
Programs must be analytically correct as well.Programs rarely work the first time they are
programmed.Programmers must perform the following on a
continual basis: analyze, experiment, correct, and redesign.
Programming languages have strict rules, known as syntax, that must be carefully followed.
The Art of Programming (2)
Slide 8
Primitive Programming (never actually in vogue) A single set of chronologically ordered steps for the computer to take
Procedural Programming Invented in 1945 by John Von Neumann
The notion of "subroutines" or "procedures" – small blocks of code that could be jumped to in any order
Earliest major procedural language: FORTRAN (1957)
Later example: C (1972)
Object-Oriented Programming Break down a programming task into objects that expose data and behavior
Late 1970s / early 1980s
Early example: C++ (1983)
Evolution of Programming
Slide 9
// The shape height and widthdouble width = 3;double height = 5;
// If these dimensions are for a rectangledouble rectangleArea = width * height;System.out.println("Rectangle area: " + rectangleArea);if (rectangleArea > 10) System.out.println(" -- it is big.");else System.out.println(" -- it is small.");
// If these dimensions are for a triangle -- the width is the base!double triangleArea = 0.5 * width * height;System.out.println("Triangle area: " + triangleArea);if (triangleArea > 10) System.out.println(" -- it is big.");else System.out.println(" -- it is small.");
Primitive Example(in Java, but don't focus on syntax)
A single set of chronologically
ordered steps for the computer to
take
Drawbacks to this?
Slide 10
// The shape height and widthdouble width = 3;double height = 5;
printRectangleArea(width, height);printTriangleArea(width, height);
static void printRectangleArea(double width, double height) { double area = width * height; System.out.print("Rectangle area: " + area); printRelativeSize(area);}
static void printTriangleArea(double width, double height) { double area = 0.5 * width * height; System.out.print("Triangle area: " + area); printRelativeSize(area);}
static void printRelativeSize(double area) { if (area > 10) System.out.println(" -- it is big."); else System.out.println(" -- it is small.");}
Procedural Example
small blocks of code that could be jumped to in any order
very small blockof "main" code
Advantages?
Drawbacks?
Slide 11
public class ShapeMaker {
public static void main(String[] args) { // The shape height and width double width = 3; double height = 5;
// Make a rectangle and print its area Rectangle myRectangle = new Rectangle(width, height); myRectangle.printArea();
// Make a triangle and print its area Triangle myTriangle = new Triangle(width, height); myTriangle.printArea(); }}
public class Rectangle {
public class Triangle {
Break down a programming task into objects that expose data and
behavior
Object Oriented Example
"If you write a computer program in an object-
oriented language, you are creating in your computer a model of some part of the
world."
Slide 12
Instances and Classes
Slide 13
Textbook Example Chapter 01 - figures
Terminology Class Circle
“Create a new Circle object”“Create a new instance of the Circle class”“Create a new object of type Circle” (less formal)
Demo: Normal circle
Make visible, move around, etc.
Big black circle (diameter 100, color black)
Small red circle (diameter 30, color red)
Inspect the object (by selecting inspect or double clicking)
Terminology “Many instances of the same class”
4demo
Slide 14
Textbook Example Chapter 01 - figures 4-5demo
classes
instances
Slide 15
Class Think: generic concept
The concept of a circle
The concept of a car
The concept of a giraffe
Instance (aka Object) Think: physical object
The green circle with a 4 cm diameter on my shirt
My blue Nissan minivan with the dent on the side
Stella, the female giraffe who lives at the Philadelphia zoo
Key Concept: Class vs. Instance
Slide 16
DATAaka “attributes”aka “state”
For example: Circle data:
Diameter, color, (x,y) location, visibility …
Car data: Make, model, year, color …
Giraffe data: Height, weight, birthday, name …
ACTIONSaka “methods”aka “functions”
For example: Circle methods: moveDown(), changeSize(), makeVisible() …
Car methods: startEngine(), reverse(), setColor() …
Giraffe methods: eat(), walk(), sleep(),setWeight() …
Classes specify types of data object store
and types of actions the objects can do
Object
Attributes (data)
Methods(behaviors / procedures)
Slide 17
Write a "recipe" to solve a problem by: Defining relevant classes
Creating instances of those classes
Defining the sequence of methods that each instance should execute
So how do we program in an object-oriented way?
Slide 18
Objects have operations which can be invoked (Java calls them methods).
Methods may have parameters to pass additional information needed to execute.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Methods and parameters5-6
Slide 19
Many instances can be created from a single class.
An instance has attributes: values stored in fields.
The class defines what fields an instance has, but each instance stores its own set of values (the state of the instance ).
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Other observations8
Slide 20Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
State8-9
Slide 21Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Two circle objects10
Slide 22
Each class has source code (Java code) associated with it that defines its details (fields and methods).
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Source code
Slide 23
Variables
Slide 24
Computer Systems: HardwareMain Memory
A section of memory is called a byte.
A section of two or four bytes is often called a word.
Main memory can be visualized as a column or row of cells.
0x0000x001
0x0030x002
0x0040x0050x0060x007
A byte is made up of 8 bits.1 0 1 0 1 0 1 0
Slide 25
public class HelloWorld{ public static void main(String[] args) { String message = "Hello World"; System.out.println(message); }}
Programming LanguagesSample Program
Key words in the sample program are:
Key words are lower case (Java is a case sensitive language). Key words cannot be used as a programmer-defined identifier. Semi-colons are used to end Java statements; however, not all lines
of a Java program end a statement. Part of learning Java is to learn where to properly use the
punctuation.
• public• class
• static• void
Slide 26
There are differences between lines and statements when discussing source code.
System.out.println(
message);This is one Java statement written using two lines. Do you
see the difference?
A statement is a complete Java instruction that causes the computer to perform an action.
Programming LanguagesLines vs Statements
Slide 27
Data in a Java program is stored in memory.Variable names represent a location in memory.Variables in Java are sometimes called fields.Variables are created by the programmer who assigns it a
programmer-defined identifier.ex: int hours = 40;
In this example, the variable hours is created as an integer (more on this later) and assigned the value of 40.
Programming LanguagesVariables
Slide 28
Variables are simply a name given to represent a place in memory.
Programming LanguagesVariables
1-28
0x0000x0010x0020x0030x0040x0050x0060x007
Slide 29
0x0000x0010x0020x0030x0040x0050x0060x007
Programming LanguagesVariables
The Java VirtualMachine (JVM)actually decideswhere the valuewill be placedin memory.
72
Assume that thisvariable declarationhas been made.int length = 72;
The variable lengthis a symbolic namefor the memorylocation 0x002.
Slide 30
The Compilerand the JVM
Slide 31
Source code
Each class has source code (Java code) associated with it that defines its details (fields and methods).
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
10
Slide 32
A programmer writes Java programming statements for a program.
These statements are known as source code.
A text editor is used to edit and save a Java source code file.
Source code files have a .java file extension.
A compiler is a program that translates source code into an executable form.
A compiler is run using a source code file as input.Syntax errors that may be in the program will be discovered
during compilation. Syntax errors are mistakes that the programmer has made
that violate the rules of the programming language.The compiler creates another file that holds the translated
instructions.
The Compiler and the Java Virtual Machine (1)
Slide 33
Most compilers translate source code into executable files containing machine code.
The Java compiler translates a Java source file into a file that contains byte code instructions.
Byte code instructions are the machine language of the Java Virtual Machine (JVM) and cannot be directly executed directly by the CPU.
The Compiler and the Java Virtual Machine (2)
Slide 34
Byte code files end with the .class file extension.
The JVM is a program that emulates a micro-processor.
The JVM executes instructions as they are read.
JVM is often called an interpreter.
Java is often referred to as an interpreted language.
The Compiler and the Java Virtual Machine
1-34
Slide 35
How Java Compiles and Interprets Code
source code(*.java files)
bytecodes(*.class files)
Java IDEOr
Text editor
Java compiler
Java interpreter
Java virtual machine (JVM)
Operating system
Java interpreter
specific to a particular operating system.
Bytecodes can run on any
platform that has a Java interpreter.
Slide 36
Program Development Process
Text editor Source code(.java)
Saves Java statements
Java compiler
Is read by
Byte code(.class)
Produces
JavaVirtual
Machine
Is interpreted by
ProgramExecution
Results in
Slide 37
Portable means that a program may be written on one type of computer and then run on a wide variety of computers, with little or no modification.
Java byte code runs on the JVM and not on any particular CPU; therefore, compiled Java programs are highly portable.
JVMs exist on many platforms:
With most programming languages, portability is achieved by compiling a program for each CPU it will run on.
Java provides an JVM for each platform so that programmers do not have to recompile for different platforms.
Portability
• Unix• BSD (Berkeley Software Distribution, UNIX derivative)• etc.
• Windows• Mac• Linux
Slide 38
Portability
Java VirtualMachine for Windows
Byte code(.class)
Java VirtualMachine for Linux
Java VirtualMachine for Mac
Java VirtualMachine for Unix
Slide 39
Using Eclipse
Slide 40
Not all of this will make sense at first.
But soon, it will become natural
In the early weeks of class, we will tend to use BlueJ to modify examples in the book and follow along
Eclipse to code from scratch
Eclipse stores all of your files in a special folder called a Workspace – which is just a regular folder on the file system
Let's make "Hello World" in Eclipse
Eclipse is an advanced IDE
Slide 41
Create a New Java Project
Using Eclipse for Java Files
Slide 42
Create a New Java Project
Use the Java Perspective in Eclipse
Using Eclipse for Java Files
Slide 43
Create a New Java Project
Use the Java Perspective in Eclipse
Highlight the project and add a package (right click)
Using Eclipse for Java Files
Slide 44
Create a New Java Project
Use the Java Perspective in Eclipse
Highlight the project and add a package (right click)
Name your package
Using Eclipse for Java Files
Slide 45
Create a New Java Project
Use the Java Perspective in Eclipse
Highlight the project and add a package (right click)
Name your package
Highlight the package & add a class (right click)
Using Eclipse for Java Files
Slide 46
Create a New Java Project
Use the Java Perspective in Eclipse
Highlight the project and add a package (right click)
Name your package
Highlight the package & add a class (right click)
Using Eclipse for Java Files
Name your class
Slide 47
/* The classic "Hello World" program */
package hello; // Packages are just a place to store related classes
/** * The purpose of the Hello class is to say "Hello World" * * Note that these comments are in the javadoc commenting style. * @author myersjac * */public class Hello {
public static void main(String[] args) { // This is how you print to the console. System.out.println("Hello World"); }
}
Hello World
Slide 48
Continuing in Eclipse…
Create a New Java Project
Call it InvoiceApp
Use the Java Perspective in Eclipse
Highlight the project and add a Java class – also named InvoiceApp
Add this code on page 37 to InvoiceApp.java
Run the code to get a 20% discount on your subtotal.
Slide 49
IOOP Glossary Terms to Know
Terms to know for tests/quizzes (see class web site)
attribute bit byte class comment
compilation compiler field instance interpreter
main method
member object* object-oriented language
single-line comment state statement statement terminator
Non-glossary terms to know
algorithm byte code JVM machine code
procedure
program variableNote: the glossary definitions are complete ones, based on a full understanding
of the material which we might not yet have. However, there are elements of the definitions that you should be able to grasp from this material.* "Object" is often defined in this fashion. While not wrong per se, the definition is incomplete and misleading as you study Java further. For our class purposes, I prefer you use the word "instance," but it is also important to know how others may use the term object.