computer programming lecture 11 - movement...
TRANSCRIPT
Computer ProgrammingLecture 11
이윤진
Lecture 11
이윤진서울대학교
2007 1 242007.1.24.
Slide Credits엄현상교수님엄현상교수님서울대학교컴퓨터공학부Computer Programming, 2007 봄학기p g g, 학기
Object-Oriented Programming (2)
순서순서JavaJava
Q&A
개Java 개요Object-Oriented Programming Language (OOPL) by Sun in Object Oriented Programming Language (OOPL) by Sun in 1991
Programming with One or More ClassesSi l St tSimple Structure
w/o header files, preprocessor, struct, operator overloading, multiple Inheritance, pointers, etc.
Garbage CollectionGarbage CollectionNo need to delete or return any storage
Dynamic LoadingCl b i l d d d dClasses being loaded as needed
Platform IndependenceJava Virtual Machine (JVM)
MultithreadingSupport for multiple threads of execution
Some Differences with C/C++Automatic Memory ManagementAutomatic Memory Management
Garbage CollectorNo Dangling Pointers or Memory Leaksg g y
No Pointer HandlingNo Explicit Reference/Dereference Operations
No MakefilesNo Header Files
cf, imported Packages
No Function Declaration (Similar to C)No Default Function Argument
Java PlatformS/W Platform for Running JavaS/W Platform for Running Java- on Top of any Platforms
Java Virtual Machine (JVM)Java Virtual Machine (JVM)Java Application Programming Interface (Java API)
Java Program
Collection of ready-made software componentsJava Program
Java Virtual Machine
Java APIJava Platform
- grouped into Packages of classes and interfaces)
Underlying Platform
Java InterpreterImplementation of the JVMImplementation of the JVM
Executing Java BytecodesJava bytecodes can be considered as intermediate code instructions for Java bytecodes can be considered as intermediate code instructions for the JVM
Java programs, once compiled into bytecodes, can be run on any JVM
How a Java Program RunsCompilation and InterpretationCompilation and Interpretation
Compiler First Translates a Java Program into Java Bytecodes OnceOnce
Interpreter Parses and Runs Each Java Bytecode Instruction Multiple times on different platforms
Java Source Code Java Bytecode Machine Code
Java Compiler Java Interpreter Computer
Java Source Code Java Bytecode Machine Code
javac Java Virtual Machine (JVM)
Java ProgramSaved in Files Each of Which Has the Same Name as the Saved in Files, Each of Which Has the Same Name as the public Class
Containing Only One public ClassContaining Only One public ClassContaining Other Non-public Classes
public class HelloWorld {public static void main(String args[]) {
This code must be saved in HelloWorld.java
System.out.println(“Hello, World”);}
}
$ javac HelloWorld.java$ java HelloWorld
compile (create HelloWorld.class; bytecode)
h JVM d h i h d$ jHello, World
start the JVM and run the main method
Memory Layout of a Java Program
Bytecode of MethodVariables in Class
Method Area public class MemoryModelTest {static int x=0;
Parameter VariableLocal Variable
Class Object
Stackstatic int x 0;public static void main(String args[]) {
int a=10, b=20, c;c = add(a b);
Array ObjectString Object
Heapc = add(a, b);
}static int add(int a, int b) {
return(a + b);return(a + b);}
}Space for objects
Sample Program: MemoryModelTest.java
created by new operator
ClassUnit of ProgrammingUnit of Programming
Java Program: a Collection of ClassesSource code in .java filesSource code in .java files
Description (Blueprint) of Objects (Instances)Common CharacteristicsCommon Characteristics
Instances Have These CharacteristicsAttributes (Data Fields) for Each ObjectAttributes (Data Fields) for Each ObjectMethods (Operations) That Work on the Objects
Member Access ControlWay to Control Access to a Class’Members from Other Way to Control Access to a Class Members from Other Classesprivatep
Accessible only in the class itself
Default (package or friendly)A ibl i th k b l f th l i th l f Accessible in the same-package subclasses of the class or in the classes of the same package
protectedAccessible in the subclasses of the class or in the classes of the same package
publicpublicAccessible everywhere
ObjectInstance of a ClassInstance of a ClassUniquely Identifiable Entity
w/ Its State, Behavior, and InterfaceS , ,Maintaining Data Values in Its AttributesReferenced by a Reference Variable (of Reference Type)
Inheriting from the Class Objectw/ a number of methodstoString() equals() & clone()toString(), equals(), … &, clone()
Managing ObjectsReferencing Objects of Specified TypesReferencing Objects of Specified Types
Objects Created by the new Operator
Creating Objects by Executing the Constructorsg j y gConstructor (Function) Overloading
Stringgreeting
String greeting = new String(″hello″);
D l ti Obj t i G b C ll ti
g
value = “hello”
g g
Deleting Objects via Garbage CollectionReference Count for Each Object
Cleanup occurs at the convenience of the Java runtime environment
Java Example: AbstractionOnline Retailer Such as Amazon ComOnline Retailer Such as Amazon.Com
Item: Type, Title, Maker, Price, Availability, etc.
class Item { // Class definition Attribute of the classclass Item { // Class definitionpublic String title; // String is a predefined classpublic double price; // double is a primitive data typepublic double SalePrice(){ return (price * 0.9);}
}M th d f th l
Item A = new Item(); // Class object definition and creation
Method of the class
Variable of reference type
// OKAY : A.title, A.price, and A.SalePrice()Variable of reference type
Java Example: EncapsulationOnline Retailer Example Cont’dOnline Retailer Example Cont d
class Item {class Item {public String title;public double price;private int inStockQuantity;
inStockQuantity attribute is not accessible outside of the Item class
public double SalePrice(){ return (price * 0.9);}public boolean isAvailable(){
if(inStockQuantity > 0) return true;else return false;else return false;
}}
I A I () // Cl bj d fi i i d iItem A = new Item(); // Class object definition and creation
// NOT OKAY: A.inStockQuantity// OKAY: A.isAvailable()// OKAY: A.isAvailable()
Java Example: InheritanceOnline Retailer Example Cont’dOnline Retailer Example Cont d
class MusicCDItem extends Item {public String singer_name;
}
Item
}
// Class object definition and creationM sicCDItem B ne M sicCDItem
MusicCDItemMusicCDItem B = new MusicCDItem;
// OKAY: B.singer_name, B.title, B.price, B.SalePrice(), // and B.isAvailable() // NOT OKAY: B.inStockQuantity
Java Example: PolymorphismOnline Retailer Example Cont’dOnline Retailer Example Cont d
class Item {public String title;public String title;public double price;private int inStockQuantity;public double SalePrice(){ return (price * 0 9);}public double SalePrice(){ return (price * 0.9);}public boolean isAvailable(){
if(inStockQuantity > 0) return true;else ret rn falseelse return false;
}public void specificInfo() {
System.out.println("no info: a base-class object");}
}
Java Example: Polymorphism Cont’d
Online Retailer Example Cont’dOnline Retailer Example Cont dclass MusicCDItem extends Item {
public String singer_name;public void specificInfo(){public void specificInfo(){
System.out.println("signer name=" + singer_name +" : a derived-class object");
}}
public class OnlineRetailer {static void printSpecificInfo(Item Item){item.specificInfo();}static void printSpecificInfo(Item Item){item.specificInfo();}public static void main(String args[]){ … }
}
Item A = new Item();Item A = new Item();MusicCDItem B = new MusicCDItem();
printSpecificInfo(A); // Call Item.specificInfo() printSpecificInfo(B); // Call MusicCDItem.specificInfo() // - Another derived class (e.g., MovieDVDItem) with specificInfo()
Static ModifierUse: Static Attributes & Static MethodsUse: Static Attributes & Static Methods
FeaturesAll Cl Sh S i M bAll Classes Share Static MembersIt Is Possible to Invoke Static Methods w/o InstantiationI St ti M th d It I All d t A N St ti D t In Static Methods, It Is Allowed to Access Non-Static Data or Non-Static Methods of Classes after the Instantiation of the ObjectsObjects
class A{private int i = 5;public static printI(){
System.out.println(i); // error!System.out.println(new A().i);
}}
’Static Modifier Cont’dDifferences between C++ and JavaDifferences between C++ and Java
Static Method InvocationC++ : Class::method();Java : Class.method();
Static Data Member InitializationC++ : No In Class Initialization (ANSI/ISO)C++ : No In-Class Initialization (ANSI/ISO)Java : In-Class Initialization
class A{public static int i = 10;
JAVAclass A{public:
C++p…
}
pstatic int i; // declare…
}}int A::i = 0; // define & initialize
Windows API
순서순서Introduction to WindowsIntroduction to Windows
What is Windows API?
A li ti D l t E i tApplication Development Environments
Message Driven System
Other Backgrounds
Function WinMain
Function WndProc
API Example : Hello, World!p
Possible Topics for Final
Introduction to WindowsHistory of WindowsHistory of Windows
85.11 Windows 1.087.11 Windows 2.092.4 Windows 3.193.7 Windows NT 3.195.8 Windows 9596.8 Windows NT 4.098 6 Wi d 9898.6 Windows 9800.2 Windows 200002 9 Windows XP02.9 Windows XP07.1 Windows Vista
’Introduction to Windows Cont’dMeritsMerits
Being the Most Widely Used in Personal ComputingGUI : Graphic User InterfaceGUI : Graphic User InterfaceMultitaskingStandard User InterfaceStandard User Interface
User Adapts to New Program Quickly
DemeritsVery Commercial Product!
Not Open Source!
[참고] X Windows: Standard Graphical Engine for Unix/Linux: Standard Graphical Engine for Unix/Linux
Difference with Microsoft WindowsPlatform IndependentNetwork Transparentp
X Protocolo Provide a client-server architecture at the application level
o Separate the processing and display for an application
- X Server : Low-level interface for controlling screen
X Client Processing part of the application- X Client : Processing part of the application
What is Windows API?API (A li i P i I f )API (Application Programming Interface)
Possibly Making Windows System Calls
Application 1
Hardware 1
Windows API Application 2
Hardware 2
Windows Application 3
Application Development EnvironmentsWindows Software Development Kit (SDK) p ( ): Providing API Libraries, Documents, Tools, etc.
Using API Directlyh f G C lHigh Performance, Fine-Grain Control
Low Productivity
Class LibrariesWrapping APIs to Classes
Convenient and PowerfulE.g., MFC (Microsoft Foundation Class) for Visual C++g , ( )
Rapid Application Development (RAD) ToolsProviding Users–Don’t-Care Visual Tools
High Productivity but Low PerformanceHigh Productivity, but Low PerformanceE.g., Visual Basic, Delphi, Power Builder, etc.
Message Driven SystemContent of a MessageContent of a Message
Event InformationChange in the SystemChange in the System
Change between the User and System
(User) Action in a Window
Role of OS Regarding a MessageInspecting What Events Have Occurred, and Generating the Corresponding MessageEnqueuing the Message into a Message Queue Belonging to E h PEach Program
’Message Driven System Cont’dUse of a Message QueueUse of a Message Queue
Each Program Has a Message QueueFunction WndProc Processes a MessageFunction WndProc Processes a Message
message queue
detect generate
enqueue
an action
OSdetect generate
message
an action
’Message Driven System Cont’dUse of the Message LoopUse of the Message Loop
LocationEnd of Function WinMainEnd of Function WinMain
FunctionalityDequeuing from the Message Queue
Translating If Necessary
Delivering to the Event Handler
’Message Driven System Cont’dreturn false if getting a WM_QUIT message, else return true
int APIENTRY WinMain(…){
translate a keyboard input …while(GetMessage(&message, 0, 0, 0)){
TranslateMessage(&message);
translate a keyboard input messagee.g.,) WM_KEYDOWN
& WM KEYUPDispatchMessage(&message);
}
& WM_KEYUP→ WM_CHAR
…} deliver the message to function
WndProc that specifies what to dop
’Message Driven System Cont’dOS Application
message queuewhile(GetMessage(&message, 0, 0, 0)){
T l t M (& )
WinMain
essage queueTranslateMessage(&message);DispatchMessage(&message);
}}
switch(message){
WndProc
WM CHAR
case WM_CHAR:…
WM_CHAR
WM_PAINT
break;case …default: return DefWindowProc();default: return DefWindowProc();
}
Other BackgroundsHandlesHandles: Variables Distinguishable from Other Resources
32 bit Integer Type Value32 bit Integer Type ValueThose Made by OS, Not the Users
Similarly, “fd=open()” in Linuxy, p ()
Types : HWND, HPEN, HBRUSH, HDC, etc.Represent a Handle of Each Resource
’Other Backgrounds Cont’dWay for PrintingWay for Printing
Application
Win32 APIGraphic
G D IGraphicDevice
Interface
Device Driver
Output Device
’Other Backgrounds Cont’dPrinting ProcedurePrinting Procedure
Get a device context handle for printing on screen
HDC hDC = GetDC(hWnd);
current Print out using the handle via GDI
TextOut(hDC,0,0,”Hello”,5);
LineTo(hDC 100 100);
window instance
LineTo(hDC,100,100);
:
Release the device context handle
R L DC(hW d hDC)ReLeaseDC(hWnd,hDC);
Function WinMainEntry Point of ProgramEntry Point of Program
Similar to “int main(int, char**);”
int APIENTRY WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance,LPSTR lpszCmdParam, int nCmdShow);LPSTR lpszCmdParam, int nCmdShow);
hInstance Instance handle of window
hPrevInstancePrevious instance handleCurrently this is always NULL
lpszCmdParam Command arguments (like argv)lpszCmdParam Command arguments (like argv)
nCmdShowShape of program(minimize, normal, maximize, …)
’Function WinMain Cont’dstartstart
create & register a window class
create a window
show the window
get a messagetranslate a message
dispatch a message
WM_QUITfalse
true
translate a message
end
Function WndProcWindow ProcedureWindow Procedure
Specify What to Do When an Event Occurs
LRESULT CALLBACK WndProc(HWND hWnd, UINT message,LRESULT CALLBACK WndProc(HWND hWnd, UINT message,WPARAM wParam, LPARAM lParam);
hWnd Instance handle of window
message Types of message
wParam Additional information of messagewParam Additional information of message(different according to message)lParam
API Example : Hello, World!Using MS Visual C++ 6 0Using MS Visual C++ 6.0
API Example : Hello, World! Cont’dMake a Workspace for the ExampleMake a Workspace for the Example
Create a ProjectSelect menu : File → New → ProjectsSelect menu : File New Projects
specify the project name
select “Win32 select Win32 Application”
API Example : Hello, World! Cont’dSelect a Default Skeleton CodeSelect a Default Skeleton Code
empty code
a simple programa simple program: having empty functions (WinMain, WndProc,…)
a simple program: displaying “Hello World!” and having a simple menu
API Example : Hello, World! Cont’dAdd a New Source File into the ProjectAdd a New Source File into the Project
Select menu : File → New → Files
specify the source file name
select “C++ Source File”
API Example : Hello, World! Cont’dSource Code
#include <windows.h>
Source Code
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);HINSTANCE g_hInst;LPSTR lpszClass="Hello, World!"; program title
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszCmdParam,int nCmdShow), p , )
{HWND hWnd;MSG Message;MSG Message;WNDCLASS WndClass;g_hInst=hInstance;
’API Example : Hello, World! Cont’dWndClass.cbClsExtra=0;
C 0WndClass.cbWndExtra=0;WndClass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRU
SH);W dCl hC L dC (NULL IDC ARROW)
register a window class
WndClass.hCursor=LoadCursor(NULL,IDC_ARROW);WndClass.hIcon=LoadIcon(NULL,IDI_APPLICATION);WndClass.hInstance=hInstance;WndClass.lpfnWndProc=(WNDPROC)WndProc;WndClass.lpszClassName=lpszClass;WndClass.lpszMenuName=NULL;
register the dispatch p ;
WndClass.style=CS_HREDRAW | CS_VREDRAW;RegisterClass(&WndClass);
create a
pprocedure
hWnd=CreateWindow(lpszClass,lpszClass,WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,
window
CW_USEDEFAULT,NULL,(HMENU)NULL,hInstance,NULL);ShowWindow(hWnd,nCmdShow);
’API Example : Hello, World! Cont’dhil (G tM g (&M g 0 0 0)) {while(GetMessage(&Message,0,0,0)) {
TranslateMessage(&Message);DispatchMessage(&Message); message DispatchMessage(&Message);
}return Message.wParam;
message loop
}
’API Example : Hello, World! Cont’dLRESULT CALLBACK WndProc(HWND hWnd,UINT message,LRESULT CALLBACK WndProc(HWND hWnd,UINT message,
WPARAM wParam,LPARAM lParam) {switch(message) {
case WM DESTROY: PostQuitMessage(0); break;case WM_DESTROY: PostQuitMessage(0); break;case WM_PAINT:
HDC hDC; PAINTSTRUCT ps; send WM QUIT
hDC = BeginPaint(hWnd, &ps);TextOut(hDC, 10, 10," Hello, World!", 14);
&
WM_QUIT to itselfwhen a window
needs repaintEndPaint(hWnd, &ps); break;
default: return DefWindowProc(hWnd,message,wParam,lParam);}return 0;
}pass the message to the default window procedure by default
’API Example : Hello, World! Cont’dCompilationCompilation
Ctrl+F7 : Compile a Source FileF7 : Build a Executable FileF7 : Build a Executable FileCtrl+F5 : Build and Execute the Program
without Debuggingwithout DebuggingF5 : Build and Execute the Program with Debugging
go(F5)
compile(Ctrl+F7) build
(F7)
execute the program
(F5)
(F7) program(Ctrl+F5)
Possible Topics for FinalUnix/LinuxUnix/Linux
C Program Memory LayoutFile System
Interprocess Communication Utilities and Editors
EmacsEmacsBatch and Shell ProgrammingC Complier and Linkerp
Static vs Shared Library Gdb & MakeModularity and Abstraction in C
Software Modular Design
’Possible Topics for Final Cont’dScopingScopingC Pointers
Call by ReferenceC y
Memory Management in C Possible Errors in Dynamic Memory Allocationy y
LibrariesStandard I/O Library
Object-Oriented ProgrammingDesign Principles
C, C++, or Java ProgrammingStatic