lecture note: java programming 1 dept. of mis, kwangwoon university >>> introduction java...
Post on 30-Dec-2015
226 Views
Preview:
TRANSCRIPT
Lecture Note: Java Programming 1 Dept. of MIS, Kwangwoon University
>>> Introduction
Java 소개
Java 개요Sample Programs
객체지향 프로그래밍 개념환경 설정 및 명령어
Lecture Note: Java Programming 2 Dept. of MIS, Kwangwoon University
>>> Introduction
Java 개요• Definition
– A general-purpose, high-level, object-oriented programming language developed by Sun Microsystems. (http://java.sun.com)
– Originally called OAK ("Green Team")
• Java 의 특성– Object-oriented
– Platform-independent (Virtual Machine; portability)
– Easy; Simplified; (no pointer, automatic garbage collection, single inheritance, ..)
– compiled/interpreted, robust, secure, multi-threaded, distributed, ...
• Compile/Execution
javac컴파일러
SourceCode
ByteCode
java
인터
프리
터
JITCompiler
MachineCode
생성 / 실행
.java .class
JVM
JRE
API classesfiles, ...
브라
우저
, or
appl
etvi
ewer interpret
Lecture Note: Java Programming 3 Dept. of MIS, Kwangwoon University
>>> Introduction
Java 개요 (Cont.)• 자바의 버젼
– Java 1.1.5: announced in 1997, improved user interface, event processing, ...
– Java2: beta-testing in 1997; Released in late 1998 (JDK 1.2); Swing, Drag&Drop, improved sound utility, ...
– Java2: SDK Standard Edition 1.3 (2000), 1.4 (2002), J2SE 5.0 (tiger), J2SE6.0(mustang), …
– http://java.sun.com
• 자바 툴– Kawa, Eclipse, ..
– Symantec Visual Cafe, Borland JBuilder, SuperCede, Rogue Wave JFactory, Natural Intelligence Roaster, Metro Works Code Warrior, SunSoft Java Workshop, …
• Related Terms– http://webopedia.internet.com/
– applet, AWT, bytecode, CGI, HotJava, interpreter, JAR, JavaBeans, JavaScript, JDBC, JDK, Jini, JIT, JNI, picoJava, Python, RMI, Smalltalk, thin client, virtual machine, JavaOS, JavaRing, JavaCard, EJB, Java Station, …
Lecture Note: Java Programming 4 Dept. of MIS, Kwangwoon University
>>> Introduction
Java 2 Standard Edition• Java 2 Standard Edition includes
– Java runtime environment: • A Java virtual machine for the platform you choose
• Java class libraries for the platform you choose
– Java compiler
– Java class library (API) documentation (as a separate download)
– Additional utilities, such as utilities for creating Java archive files (JAR files) and for debugging Java technology programs
– Examples of Java technology programs
Lecture Note: Java Programming 5 Dept. of MIS, Kwangwoon University
>>> Introduction
Product Life Cycle• Seven Stages
– Analysis: investigate a problem and determine its scope and major components
– Design: create blueprints (specs) for components that will be developed
– Development
– Testing: unit tests (individually) and integrated test (together)
– Implementation: ship a product, making the product available to customers
– Maintenance
– End-of-life (EOL)
Lecture Note: Java Programming 6 Dept. of MIS, Kwangwoon University
>>> Introduction
A Sample Program• a Java program
– source program• .java
• text file format
• pico, vi, emacs, ... in Unix; notepad, edit, ... in Windows
class HelloWorld {
// 주석 부분 public static void main (String args[]){
String msg = "World";
System.out.print("Hello ");System.out.println(msg);
}}
– javac HelloWorld.java• creates HelloWorld.class
– java HelloWorld
#include <stdio.h>
char msg[ ]={‘W’,‘o’,‘r’,‘l’,‘d’};/* comments here */main (int argc, char **argv) {
printf(“Hello ”); printf(“%s\n”, msg);}
참고 : C program
Lecture Note: Java Programming 7 Dept. of MIS, Kwangwoon University
>>> Introduction
Object-oriented Programming• Program
– a set of classes and interactions among them
– not procedure-oriented
• Class– a framework for objects (or instances) of similar characteristics
– properties (or, attributes, status variables)
– behavior (or, method, function)• retrieve/update the attribute values of instances, execute an action, etc
– Class example: Student, Employee, Vehicle, Truck, ...
• Example: a monster, called Jabberwock, in a storybook– Making a class for Jabberwork : a simplest form
class Jabberwock { }
– Attributes• color (orange, yellow, ...), sex (m, f), status (full, hungry), …
– Behavior• get angry, cool down, eat a peasant, skip a meal, take a rest, …
Lecture Note: Java Programming 8 Dept. of MIS, Kwangwoon University
>>> Introduction
Jabberwock 예제• 속성 추가
class Jabberwock {String color; // 표준 클래스
String sex;boolean hungry; // true 또는 false 값
}
• Method 추가 : 먹이주기void feedJabberwock( ) {
if (hungry == true) {
System.out.println("Yum -- a peasant!");
hungry = false;
} else
System.out.println("No, thanks -- already ate.");
}
Lecture Note: Java Programming 9 Dept. of MIS, Kwangwoon University
>>> Introduction
Jabberwock 예제 (Cont.)• Method 추가 : 속성 보여주기
void showAttributes( ) {
System.out.println ("This is a " + sex + " " + color + " jabberwock.");
if (hungry == true)
System.out.println("The jabberwock is hungry.");
else
System.out.println("The jabberwock is full.");
}
Lecture Note: Java Programming 10 Dept. of MIS, Kwangwoon University
>>> Introduction
Jabberwock 예제 (Cont.)• 클래스 완성 (?)
class Jabberwock { String color; String sex; boolean hungry;
void feedJabberwock() { if (hungry == true) { System.out.println("Yum -- a peasant!"); hungry = false; } else System.out.println("No, thanks -- already ate."); }
void showAttributes() { System.out.println("This is a " + sex + " " + color + " jabberwock."); if (hungry == true) System.out.println("The jabberwock is hungry."); else System.out.println("The jabberwock is full."); }
}
Lecture Note: Java Programming 11 Dept. of MIS, Kwangwoon University
>>> Introduction
Jabberwock 예제 (Cont.)• % javac Jabberwock.java
% java JabberwockIn class Jabberwock: void main (String argv[ ]) is not defined
• 방안– main( ) 메쏘드에서 Jabberwock 클래스를 이용하도록 한다
• main ( ) 메쏘드를 Jabberwock 클래스에 추가 , or • main( ) 메쏘드를 갖는 새로운 클래스를 만든다
public static void main (String arguments[]) { Jabberwock j = new Jabberwock( ); // 새로운 객체 생성 j.color = "orange"; j.sex = "male"; j.hungry = true; // 객체 이용 System.out.println("Calling showAttributes ..."); j.showAttributes( ); // 객체 이용 System.out.println("-----"); System.out.println("Feeding the jabberwock ..."); j.feedJabberwock( ); System.out.println("-----"); System.out.println("Calling showAttributes ..."); j.showAttributes( ); System.out.println("-----"); System.out.println("Feeding the jabberwock ..."); j.feedJabberwock( ); }
Lecture Note: Java Programming 12 Dept. of MIS, Kwangwoon University
>>> Introduction
Java Applet• Java Application 과 Java Applet
– main class
• javac Hello.java
• appletviewer hello.htm 실행 , 또는 웹 브라우저로 hello.html 열기import java.awt.*;import java.applet.*;Import java.util.*;
public class Clock extends Applet { private String greeting[] = { "Hello, world" };
public void paint(Graphics g) { g.drawString(greeting[0], 25, 25); }}
<html><head><title>Hello</title></head><body><applet code=Hello.class width=250 height=250></applet></body></html>
Hello.java Hello.html
Lecture Note: Java Programming 13 Dept. of MIS, Kwangwoon University
>>> Introduction
Java 객체지향 프로그래밍 (Cont.)
• 상속성 (Inheritance)
– 한 클래스가 다른 클래스로부터 속성과 메쏘드를 물려받는 성질
– superclass; subclass; inheritance hierarchy;
– Object 클래스
– method overriding
– subclassing
• 패키지 (Package)
– 관련된 클래스와 인터페이스의 그룹핑 • 인터페이스 (Interface): 추상 메쏘드만 갖는 특별한 형태의 클래스
– java.lang 패키지 : 표준 java 클래스
– 다른 클래스의 참조• import java.awt.Color 또는 import java.awt.*
• import java.applet.*
Lecture Note: Java Programming 14 Dept. of MIS, Kwangwoon University
>>> Introduction
Applet 예제 2: Palindrome • 어떤 문장을 display 하는 애플릿 프로그램 작성• 애플릿 정의
public class Palindrome extends java.applet.Applet {
}– 모든 애플릿 클래스는 public 선언
• 폰트 객체 생성Font f = new java.awt.Font("TimesRoman", Font.BOLD, 36);
• 애플릿이 상속 받는 메쏘드– 애플릿 실행 준비 , 마우스 입력 대응 , 애플릿 표시 , 실행 종료용 , ...
– paint ( ) 메쏘드의 재정의 (overriding)
public void paint(Graphics screen) { // Learn later about Graphics class screen.setFont(f); screen.setColor(Color.red); screen.drawString("Go hang a salami, I'm a lasagna hog.", 5, 40);
}
Lecture Note: Java Programming 15 Dept. of MIS, Kwangwoon University
>>> Introduction
Subclassing 예제 : Palindrome • a complete program
import java.awt.Graphics;import java.awt.Font;import java.awt.Color;import.applet.*
public class Palindrome extends Applet { Font f = new Font("TimesRoman", Font.BOLD, 36);
public void paint(Graphics screen) { screen.setFont(f); screen.setColor(Color.red); screen.drawString("Go hang a salami, I'm a lasagna hog.", 5, 40); }}
• <APPLET CODE="Palindrome.class" WIDTH=600 HEIGHT=100></APPLET>
Lecture Note: Java Programming 16 Dept. of MIS, Kwangwoon University
>>> Introduction
환경 설정• JDK 설치 디렉토리
– bin
• javac, java, appletviewer, jar, javah, javap, javadoc, ...
– demo, jre, include, lib, …
• 명령어 경로 지정 (path 변수 )
– javac, java, appletviewer, ...
– Windows 98 예 • autoexec.bat 화일에 set path=%path%; c:\jdk1.4\bin 추가
• 실행 sysedit
– NT/2000, XP 예 • 설정 제어 시스템 고급 탭 에서 path 변수값 변경
– Unix 예 • .cshrc (or .tcshrc) 화일에 set path=($path /usr/local/java/bin) 추가
Lecture Note: Java Programming 17 Dept. of MIS, Kwangwoon University
>>> Introduction
환경 설정 (Cont.)
• 클래스 경로 지정 (CLASSPATH 변수 )
– JDK1.2 이전 버젼의 경우
• set CLASSPATH=.;c:\jdk1.1.7\lib\classes.zip [Windows 의 path 설정참조 ]
• setenv JAVA_HOME /usr/local/jdk
setenv CLASSPATH .:$JAVA_HOME/lib/classes.zip [Unix]
– JDK1.2 이후 버전의 경우
• CLASSPATH 변수를 두지 않거나 또는 . 만 포함해도 됨
– refer to the readme file or installation documents from java.sun.com
• explore.kwangwoon.ac.kr 에 홈페이지 만들기
– Refer to http://explore.kwangwoon.ac.kr
– public_html directory
– explore 서버의 환경은 ? (JDK 버젼 ? 명령어 위치 ? 환경변수 설정 ? ...)
Lecture Note: Java Programming 18 Dept. of MIS, Kwangwoon University
>>> Introduction
환경 설정 (Cont.)• Basic Unix commands
– ls [-al] [files] ---- list information of files
– more filename ---- display the content of a file ( 긴 화일일때 Space 키 , b, q, /, ..)
– cd [path] ---- change the current directory ( 절대 / 상대 경로 )
– mkdir dirname ---- create a directory ( 디렉토리의 삭제 rmdir, 화일삭제 rm )
– chmod [ugo][rwx] file ------ change the permission mode of a file
– pico filename
– vi [filename] ----- cursor-based screen editor• 이동 : h, j, k, l, ^f, ^b, ^u, ^d
• 입력 / 변경 : i, a, I, A, c, cw, cc, ( 입력모드 종료시 ESC 키 필요 )
• 삭제 : x, dw, dd, 5x, 5cw, 5dd ( 붙여넣기 p 직전명령취소 u 직전명령반복 . )
• 저장 / 종료 : :w, ZZ, :wq!, :q!
– man 명령어 ---- on-line 매뉴얼– logout ( 또는 exit)
Lecture Note: Java Programming 19 Dept. of MIS, Kwangwoon University
>>> Introduction
javac 컴파일러• Compiles Java source code into Java bytecodes that can then be used by the
java interpreter, Web browsers, and appletviewers.
• 용법javac [options] [source files] [@sourcelist]
• .java extension for source file names
• Classname.java, if the class is public or is referenced from another source file.
• Generates .class file for every class defined in each source file
• examplesjavac MyProgram.java javac -classpath .:/home/avh/classes:/usr/local/java/classes MyProgram.java javac -d /home/avh/classes MyProgram.java (package 위치 지정 )
• 기타 옵션-g for debugging (jdb)
-encoding … source files encoding name (e.g., KSC5601, SJIS, …)
• man javac
Lecture Note: Java Programming 20 Dept. of MIS, Kwangwoon University
>>> Introduction
java 인터프리터 & javap
• 용법java [options] class 이름 [argument ...]
option: -Dproperty=value
• JIT compiler– Sun Microsystems, Asymetrix SuperCede VM, Kaffe bytecode interpreter, Micr
osoft SDK 2.0 VM, Symantec JIT compiler, ...
– 강의노트의 JITintro.htm 문서 참조
• To disable or override the default JIT compiler – setenv JAVA_COMPILER NONE ( 또는 다른 이름 )
– % java -Djava.compiler=none class 이름
• javap– disassemble the class files
– fields, methods, variables,
– De-compile of bytecode is possible (source is disclosed)
Lecture Note: Java Programming 21 Dept. of MIS, Kwangwoon University
>>> Introduction
jar• jar - Java archive tool
– a Java application that combines multiple files into a single JAR archive file.
– also a general-purpose archiving and compression tool, based on ZIP and the ZLIB compression format.
• SYNOPSIS
jar [ -c ] [ -f ] [ -t ] [ -v ] [ -x file ]
[ manifest-file ] destination input-file [ input-files ]
• example% jar cvf myJarFile *.class
• Manifest file – meta-information about the archive
– automatically generated by the jar tool
– always the first entry in the jar file
– by default, META-INF/MANIFEST.INF
• c.f., tar command in Unix
• % man jar
Lecture Note: Java Programming 22 Dept. of MIS, Kwangwoon University
>>> Introduction
기타 명령어• appletviewer URL_of_HTML
• jdb– dbx, gdb like command-line debugger
• javah– generates C header and source files that are needed to implement native method
s.
• javadoc– Java API Documentation Generator
– parses the declarations and comments in a set of Java source files and produces a set of HTML pages describing, by default, the public and protected classes, interfaces, constructors, methods, and fields.
• javakey– Java security tool which is primarily used to generate digital signatures for archi
ve files.
• javaverify
Lecture Note: Java Programming 23 Dept. of MIS, Kwangwoon University
>>> Introduction
Some Tips
• Java is case-sensitive
• Hello.java.txt when editing in notepad
• 여러 클래스로 구성된 화일의 컴파일과 실행– javac file1.java file2.java ...
– java class_file_having_main_function
• public class– at most one for each file
– the same file name as the class name (except suffix)
• naming convention– MyClassName
– System.out.println
– myFirstMethod
Lecture Note: Java Programming 24 Dept. of MIS, Kwangwoon University
>>> Introduction
연 습 Unix 환경과 Windows 환경에서 각각 다음 내용을 실시하라
- 자신의 홈 디렉토리 ( 또는 ' 내문서 ') 아래에 java_work 디렉토리를
생성하고
- Jabberwock 와 Palindrome 클래스를
작성하여 실행시켜보라 .
Hello.java 의 화일명을 hello.java 로
바꿔서 컴파일하면 ? 또 , Hello.html 에
애플릿 태그가 여러 개 있을 때 , appletviewer Hello.html 의 결과는 ?
jar 명령을 이용하여 압축저장 / 내용보기 / 추출 등을 연습해보라 .
javap, javaverify 등의 각 명령어들을 이용해보고 , Unix 에서 man
명령을 이용하여 on-line 매뉴얼을 살펴보라 .
Java Application Java Applet
Windows DOS browser or appletviewerWindows Kawa
Unix browser
UnixWindows
Lecture Note: Java Programming 25 Dept. of MIS, Kwangwoon University
>>> Introduction
과제 #1
[ 과제 1-2] ‘ 시계’라고 하는 클래스를 생각해보라 . ( 이름 추가할 것 )
1. 어떤 attribute 들이 있겠는가 ? (3 개 이상 ) 그리고 각 attribute 의 가능한
값은 무엇인가 ?
2. 어떤 method 들이 있겠는가 ? (3 개 이상 )
( 날짜 출력하는 프로그램 , Applet+Application, bollen charged charged=false
d, 출력불가 메시지 출력 , 시계 color = )
Due: 다음 주 – URL 강의게시판에 등록 ( 과제제출 – 애플릿만 )
소스코드와 실행스샷은 첨부로 (DOC 로 몰아서 ~!) (9/17 까지 )
top related