Microsoft PowerPoint - java

Similar documents
1

Microsoft PowerPoint - chap11

Microsoft PowerPoint - java2 [호환 모드]

PowerPoint 프레젠테이션

gnu-lee-oop-kor-lec06-3-chap7

PowerPoint 프레젠테이션

JAVA PROGRAMMING 실습 08.다형성

JVM 메모리구조

02 C h a p t e r Java

강의10

01-OOPConcepts(2).PDF

PowerPoint 프레젠테이션

Design Issues

쉽게 풀어쓴 C 프로그래밍

Microsoft Word - FunctionCall

Java ~ Java program: main() class class» public static void main(string args[])» First.java (main class ) /* The first simple program */ public class

PowerPoint 프레젠테이션

C# Programming Guide - Types

Microsoft PowerPoint - 2강

6주차.key

5장.key

구문 분석

슬라이드 1

자바 프로그래밍

ilist.add(new Integer(1))과 같이 사용하지 않고 ilist.add(1)과 같이 사용한 것은 자바 5.0에 추가된 기본 자료형과 해당 객체 자료 형과의 오토박싱/언박싱 기능을 사용한 것으로 오토박싱이란 자바 컴파일러가 객체를 요구하는 곳에 기본 자료형

PowerPoint Presentation

Semantic Consistency in Information Exchange

Cluster management software

예외 예외정의예외발생예외처리예외전파 단정 단정의선언 단정조건검사옵션 2

예제 2) Test.java class A intvar= 10; void method() class B extends A intvar= 20; 1"); void method() 2"); void method1() public class Test 3"); args) A

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

untitled

제11장 프로세스와 쓰레드

초보자를 위한 자바 2 21일 완성 - 최신개정판

rmi_박준용_final.PDF

PowerPoint Presentation

Microsoft Word - ExecutionStack

9장.예외와 단정

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

PowerPoint Presentation

09-interface.key

thesis

03-JAVA Syntax(2).PDF

No Slide Title

Deok9_Exploit Technique

JAVA PROGRAMMING 실습 02. 표준 입출력

본문01

Modern Javascript

PowerPoint 프레젠테이션

Microsoft PowerPoint - 04-UDP Programming.ppt

#Ȳ¿ë¼®

PowerPoint Presentation

Runtime Data Areas 엑셈컨설팅본부 /APM 팀임대호 Runtime Data Area 구조 Runtime Data Area 는 JVM 이프로그램을수행하기위해할당받는메모리영역이라고할수있다. 실제 WAS 성능문제에직면했을때, 대부분의문제점은 Runtime Da

Page 2 of 6 Here are the rules for conjugating Whether (or not) and If when using a Descriptive Verb. The only difference here from Action Verbs is wh

No Slide Title

Chap7.PDF

슬라이드 1

Something that can be seen, touched or otherwise sensed

PowerPoint 프레젠테이션

JAVA PROGRAMMING 실습 07. 상속

example code are examined in this stage The low pressure pressurizer reactor trip module of the Plant Protection System was programmed as subject for

Chap06(Interprocess Communication).PDF

Microsoft PowerPoint - PL_03-04.pptx

Contents Contents 2 1 Abstract 3 2 Infer Checkers Eradicate Infer....

Microsoft PowerPoint - java1 [호환 모드]

PowerPoint Presentation

No Slide Title

Microsoft Word - java19-1-midterm-answer.doc

chap10.PDF

초보자를 위한 C# 21일 완성

JAVA PROGRAMMING 실습 09. 예외처리

The_IDA_Pro_Book

제 1 강 희망의 땅, 알고리즘

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

신림프로그래머_클린코드.key

<B3EDB9AEC1FD5F3235C1FD2E687770>

PowerPoint Template

PowerPoint 프레젠테이션

10.0pt1height.7depth.3width±â10.0pt1height.7depth.3widthÃÊ10.0pt1height.7depth.3widthÅë10.0pt1height.7depth.3width°è10.0pt1height.7depth.3widthÇÁ10.0pt1height.7depth.3width·Î10.0pt1height.7depth.3width±×10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width¹Ö pt1height.7depth.3widthŬ10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width½º, 10.0pt1height.7depth.3width°´10.0pt1height.7depth.3widthü, 10.0pt1height.7depth.3widthº¯10.0pt1height.7depth.3width¼ö, 10.0pt1height.7depth.3width¸Þ10.0pt1height.7depth.3width¼Ò10.0pt1height.7depth.3widthµå

10송동수.hwp

PowerPoint Presentation

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345])

비긴쿡-자바 00앞부속

11 템플릿적용 - Java Program Performance Tuning (김명호기술이사)

11¹Ú´ö±Ô

05-class.key

Microsoft PowerPoint - a10.ppt [호환 모드]

1. auto_ptr 다음프로그램의문제점은무엇인가? void func(void) int *p = new int; cout << " 양수입력 : "; cin >> *p; if (*p <= 0) cout << " 양수를입력해야합니다 " << endl; return; 동적할

MasoJava4_Dongbin.PDF

Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

Microsoft PowerPoint - ch07 - 포인터 pm0415

쉽게 풀어쓴 C 프로그래밍

solution map_....

JUNIT 실습및발표

PowerPoint 프레젠테이션

final_thesis

Microsoft PowerPoint - lec2.ppt

Vol.257 C O N T E N T S M O N T H L Y P U B L I C F I N A N C E F O R U M

chap 5: Trees

Transcription:

Java John Mitchell & Byeong-Mo Chang

Outline Language Overview History and design goals Classes and Inheritance Object features Encapsulation Inheritance Types and Subtyping Primitive and ref types Interfaces; arrays Exception hierarchy Subtype polymorphism and generic programming Virtual machine overview Loader and initialization Linker and verifier Bytecode interpreter Bytecode bytecodes

Origins of the language James Gosling and others at Sun, 1990-95 Oak language for set-top box small networked device with television display graphics execution of simple programs communication between local program and remote site no expert programmer to deal with crash, etc. Internet application simple language for writing programs that can be transmitted over network

Design Goals Portability Internet-wide distribution: PC, Unix, Mac Reliability Avoid program crashes and error messages Safety Programmer may be malicious Simplicity and familiarity Appeal to average programmer; less complex than C++ Efficiency Important but secondary

General design decisions Simplicity Almost everything is an object All objects on heap, accessed through pointers No functions, no multiple inheritance, no go to, no operator overloading, few automatic coercions Portability and network transfer Bytecode interpreter on many platforms Reliability and Safety Typed source and typed bytecode language Run-time type and bounds checks Garbage collection

Java System The Java programming language Compiler and run-time system Programmer compiles code Compiled code transmitted on network Receiver executes on interpreter (JVM) Safety checks made before/during execution Library, including graphics, security, etc. Large library made it easier for projects to adopt Java Interoperability Provision for native methods

Java Release History 1995 (1.0) First public release 1997 (1.1) Nested classes Support for function objects 2001 (1.4) Assertions Verify programmers understanding of code 2004 (1.5) Tiger Generics, foreach, Autoboxing/Unboxing, Typesafe Enums, Varargs, Static Import, Annotations, concurrency utility library http://java.sun.com/developer/technicalarticles/releases/j2se15/ Improvements through Java Community Process

Outline Objects in Java Classes, encapsulation, inheritance Type system Primitive types, interfaces, arrays, exceptions Virtual machine Loader, verifier, linker, interpreter Bytecodes

Language Terminology Class, object - as in other languages Field data member Method - member function Static members - class fields and methods this - self Package - set of classes in shared namespace Native method - method written in another language, often C

Java Classes and Objects Syntax similar to C++ Object has fields and methods is allocated on heap, not run-time stack accessible through reference (only ptr assignment) garbage collected Dynamic lookup Similar in behavior to other languages Static typing => more efficient than Smalltalk Dynamic linking, interfaces => slower than C++

Point Class class Point { private int x; protected void setx (int y) {x = y;} public int getx() {return x;} Point(int xval) {x = xval;} // constructor }; Visibility similar to C++, but not exactly (later slide)

Object initialization Java guarantees constructor call for each object Memory allocated Constructor called to initialize memory Some interesting issues related to inheritance We ll discuss later Cannot do this (would be bad C++ style anyway): Obj* obj = (Obj*)malloc(sizeof(Obj)); Static fields of class initialized at class load time Talk about class loading later

Encapsulation and packages Every field, method belongs to a class Every class is part of some package Can be unnamed default package File declares which package code belongs to package class field method package class field method

Visibility and access Four visibility distinctions public, private, protected, package Method can refer to private members of class it belongs to non-private members of all classes in same package protected members of superclasses (in diff package) public members of classes in visible packages Visibility determined by files system, etc. (outside language) Qualified names (or use import) java.lang.string.substring() package class method

Inheritance Similar to Smalltalk, C++ Subclass inherits from superclass Single inheritance only (but Java has interfaces) Some additional features Conventions regarding super in constructor and finalize methods Final classes and methods

Example subclass class ColorPoint extends Point { // Additional fields and methods private Color c; protected void setc (Color d) {c = d;} public Color getc() {return c;} // Define constructor ColorPoint(int xval, Color cval) { super(xval); // call Point constructor c = cval; } // initialize ColorPoint field };

메쏘드재정의 (Method overriding) 메쏘드재정의란무엇인가? 자식클래스가상속된메쏘드를자신이원하는대로재정의하는것 새로운메쏘드는부모메쏘드와이름과서명 (signature) 이같아야한다. 메쏘드의서명 (signature) 메쏘드의매개변수이름, 개수, 순서, 타입 재정의된메쏘드실행 그메쏘드를실행하는객체의타입에따라호출될메쏘드가결정된다.

메쏘드재정의 : 예 class Fruit { int grams; int cals_per_gram; } int total_calories( ) { /* */ } void peel( ) { System.out.print( peel a Fruit ); } class Lemon extends Fruit { void squeeze( ) { /* */ } // Fruit 클래스의 peel() 메쏘드를 Lemon 클래스가재정의 void peel( ) { super.peel(); System.out.println(, which is a lemon ); } }

메쏘드재정의 : 예 class Example { public static void main(string args[]) { Fruit fruit = new Fruit(); Lemon lemon = new Lemon(); fruit.peel(); lemon.peel(); } } fruit = lemon; fruit.peel();

중복정의 vs. 재정의 중복정의 한클래스내에같은이름의여러개의메쏘드 서로다른서명을갖는경우 비슷한연산을다른매개변수에대해서다른방식으로정의하는데사용 재정의 부모클래스의메쏘드를자식클래스가재정의 서명이같아야한다. 시그너처가다르다면어떻게될까?

super 참조 super 는슈퍼클래스를지칭하는참조 슈퍼클래스의멤버필드나메소드를지칭할때사용 super.field super.method() super() super() 는슈퍼클래스의생성자를호출 super() 는생성자의맨처음부분에위치 서브클래스생성자에서슈퍼클래스의생성자를호출

바인딩 (Binding) 바인딩이란무엇인가? 이름이가리키는대상을결정하는것 obj.doit(); 이호출은호출될메쏘드를결정즉바인딩한다. 컴파일시간에결정하면언제나같은메쏘드가호출될것이다. 동적바인딩 (dynamic binding) 그러나 Java는동적바인딩을한다 runtime binding, late binding 이라고도한다. 왜동적바인딩을하는가? 프로그램설계에유연성을제공한다.

다형성 (Polymorphism) 다형성 (polymorphism) 의의미 많은형태를갖는다. "having many forms 다형참조 (polymorphic reference) 변수 때에따라다른타입의객체를참조할수있다. 다형참조를통해호출된메쏘드는호출할때마다다를수있다. Java에서모든객체참조는다형적일수있다.

다형참조 객체참조변수 선언된클래스의객체와 선언된클래스의자손클래스의객체를참조할수있다. 예 : Fruit Lemon Fruit fruit; if ( ) fruit = new Fruit(); else fruit = new Lemon(); fruit.peel();

동적바인딩 호출될메쏘드결정 참조변수의타입이아니고 실행시간에참조되고있는객체의타입에의해결정된다. fruit.peel(); fruit 가 Fruit 객체를참조하는경우 Fruit peel() Fruit 의 peel 호출 fruit 가 Lemon 객체를참조하는경우 Lemon 의 peel 호출 Lemon peel()

Class Object Every class extends another class Superclass is Object if no other class named Methods of class Object GetClass return the Class object representing class of the object ToString returns string representation of object equals default object equality (not ptr equality) hashcode Clone makes a duplicate of an object wait, notify, notifyall used with concurrency finalize

Final classes and methods Restrict inheritance Final classes and methods cannot be redefined Example java.lang.string Reasons for this feature Important for security Programmer controls behavior of all subclasses Critical because subclasses produce subtypes Compare to C++ virtual/non-virtual Method is virtual until it becomes final

Outline Objects in Java Classes, encapsulation, inheritance Type system Primitive types, interfaces, arrays, exceptions Virtual machine Loader, verifier, linker, interpreter Bytecodes

Java Types Two general kinds of times Primitive types not objects Integers, Booleans, etc Reference types Classes, interfaces, arrays No syntax distinguishing Object * from Object Static type checking Every expression has type, determined from its parts Some auto conversions, many casts are checked at run time Example, assuming A <: B Can use A x and type If B x, then can try to cast x to A Downcast checked at run-time, may raise exception

Classification of Java types Reference Types Object Object[ ] Throwable Shape Shape[ ] Circle Square Circle[ ] Square[ ] user-defined arrays Exception types Primitive Types boolean int byte float long

Subtyping Primitive types Conversions: int -> long, double -> long, Class subtyping similar to C++ Subclass produces subtype Single inheritance => subclasses form tree Interfaces Completely abstract classes no implementation Multiple subtyping Interface can have multiple subtypes (extends, implements) Arrays Covariant subtyping not consistent with semantic principles

Java class subtyping Signature Conformance Subclass method signatures must conform to those of superclass Three ways signature could vary Argument types Return type Exceptions How much conformance is needed in principle? Java rule Java 1.1: Arguments and returns must have identical types, may remove exceptions Java 1.5: covariant return type specialization

Interface subtyping: example interface Shape { public float center(); public void rotate(float degrees); } interface Drawable { public void setcolor(color c); public void draw(); } class Circle implements Shape, Drawable { // does not inherit any implementation // but must define Shape, Drawable methods }

Properties of interfaces Flexibility Allows subtype graph instead of tree Avoids problems with multiple inheritance of implementations (remember C++ diamond ) Cost Offset in method lookup table not known at compile Different bytecodes for method lookup one when class is known one when only interface is known search for location of method cache for use next time this call is made (from this line)

Array types Automatically defined Array type T[ ] exists for each class, interface type T Cannot extended array types (array types are final) Multi-dimensional arrays as arrays of arrays: T[ ] [ ] Treated as reference type An array variable is a pointer to an array, can be null Example: Circle[] x = new Circle[array_size] Anonymous array expression new int[] {1,2,3,... 10} Every array type is a subtype of Object[ ], Object Length of array is not part of its static type

Array subtyping Covariance if S <: T then S[ ] <: T[ ] Standard type error class A { } class B extends A { } B[ ] barray = new B[10] A[ ] aarray = barray // considered OK since B[] <: A[] aarray[0] = new A() // compiles, but run-time error // raises ArrayStoreException

Covariance problem again Remember Simula problem If A <: B, then A ref <: B ref Needed run-time test to prevent bad assignment Covariance for assignable cells is not right in principle Explanation interface of T reference cell is put : T T ref get : T ref T Remember covariance/contravariance of functions

Outline Objects in Java Classes, encapsulation, inheritance Type system Primitive types, interfaces, arrays, exceptions Virtual machine Loader, verifier, linker, interpreter Bytecodes

Java Implementation Compiler and Virtual Machine Compiler produces bytecode Virtual machine loads classes on demand, verifies bytecode properties, interprets bytecode Why this design? Bytecode interpreter/compilers used before Pascal pcode ; Smalltalk compilers use bytecode Minimize machine-dependent part of implementation Do optimization on bytecode when possible Keep bytecode interpreter simple For Java, this gives portability Transmit bytecode across network

Java Virtual Machine Architecture A.java Java Compiler Compile source code A.class B.class Network Java Virtual Machine Loader Verifier Linker Bytecode Interpreter

JVM memory areas Java program has one or more threads Each thread has its own stack All threads share same heap method area heap Java stacks PC registers native method stacks

Class loader Runtime system loads classes as needed When class is referenced, loader searches for file of compiled bytecode instructions Default loading mechanism can be replaced Define alternate ClassLoader object Extend the abstract ClassLoader class and implementation ClassLoader does not implement abstract method loadclass, but has methods that can be used to implement loadclass Can obtain bytecodes from alternate source VM restricts applet communication to site that supplied applet

Example issue in class loading and linking: Static members and initialization class... { /* static variable with initial value */ static int x = initial_value /* ---- static initialization block --- */ static { /* code executed once, when loaded */ } } Initialization is important Cannot initialize class fields until loaded Static block cannot raise an exception Handler may not be installed at class loading time

JVM Linker and Verifier Linker Adds compiled class or interface to runtime system Creates static fields and initializes them Resolves names Checks symbolic names and replaces with direct references Verifier Check bytecode of a class or interface before loaded Throw VerifyError exception if error occurs

Verifier Bytecode may not come from standard compiler Evil hacker may write dangerous bytecode Verifier checks correctness of bytecode Every instruction must have a valid operation code Every branch instruction must branch to the start of some other instruction, not middle of instruction Every method must have a structurally correct signature Every instruction obeys the Java type discipline Last condition is fairly complicated.

Bytecode interpreter Standard virtual machine interprets instructions Perform run-time checks such as array bounds Possible to compile bytecode class file to native code Java programs can call native methods Typically functions written in C Multiple bytecodes for method lookup invokevirtual - when class of object known invokeinterface - when interface of object known invokestatic - static methods invokespecial - some special cases

Type Safety of JVM Run-time type checking All casts are checked to make sure type safe All array references are checked to make sure the array index is within the array bounds References are tested to make sure they are not null before they are dereferenced. Additional features Automatic garbage collection No pointer arithmetic If program accesses memory, that memory is allocated to the program and declared with correct type

Java Sandbox Four complementary mechanisms Class loader Separate namespaces for separate class loaders Associates protection domain with each class Verifier and JVM run-time tests NO unchecked casts or other type errors, NO array overflow Preserves private, protected visibility levels Security Manager Called by library functions to decide if request is allowed Uses protection domain associated with code, user policy Recall: stack inspection problem on midterm

Outline Objects in Java Classes, encapsulation, inheritance Type system Primitive types, interfaces, arrays, exceptions Virtual machine Loader, verifier, linker, interpreter Bytecodes

JVM 의데이터타입 기초타입 (Primitive types) 정수관련타입 byte(8 bits), short(16 bits), int(32 bits), long(64 bits), char(16 bits, UNICODE) 부동소수점 : float(32 bits), double(64 bits) boolean : true /false returnaddress : 바이트코드명령어주소 참조타입 (Reference types) 클래스 (class) 배열 (array) 인터페이스9interface)

바이트코드명령어 8- 비트연산코드를갖는 202 개명령어 스택기반실행 오퍼랜드스택을사용 명령어실행전오퍼랜드들을스택에적재하고결과값도스택에적재 레지스터는없고대신에지역변수사용 오퍼랜드타입명시 iadd : 정수덧셈 복잡한명령어들 메모리할당 모니터 / 쓰레드동기화 메쏘드호출

바이트코드명령어카테고리 Category No. Example arithmetic operation 24 iadd, lsub, frem logical operation 12 iand, lor, ishl numeric conversion 15 int2short, f2l, d2i pushing constant 20 bipush, sipush, ldc, iconst_0, fconst_1 stack manipulation 9 pop, pop2, dup, dup2 flow control instructions 28 goto, ifne, ifge, if_null, jsr, ret managing local variables 52 astore, istore, aload, iload, aload_0 manipulating arrays 17 aastore, bastore, aaload, baload creating objects and array 4 new, newarray, anewarray, multianewarry object manipulation 6 getfield, putfield, getstatic, putstatic method call and return 10 invokevirtual, invokestatic, areturn miscellaneous 5 throw, monitorenter, breakpoint, nop

바이트코드명령어타입 타입힌트 iadd, isub, istore,... 실행전타입검사가능 보다안전한시스템가능 타입접두사없는명령어 pop, dup, invokevirtual, type int long float double byte char short reference code i l f d b c s a

예 : 자바코드 static int factorial(int n) { int res; for (res = 1; n > 0; n--) res = res * n; return res; }

예 : 바이트코드 0: iconst 1 // push 1 1: istore 1 // store it in register 1 ( 변수 res) 2: iload 0 // push register 0 ( 매개변수 n) 3: ifle 14 // if negative or null, goto PC 14 6: iload 1 // push register 1 (res) 7: iload 0 // push register 0 (n) 8: imul // mutiply the two integers at top of stack 9: istore 1 // pop result and store it in register 1 (res) 10: iinc 0, 01 // decrement register 0 (n) by 1 11: goto 2 // goto PC 2 14: iload 1 // load register 1 (res) 15: ireturn // return its value to caller

자바스택및메쏘드호출 쓰레드당하나의자바스택 자바스택위에스택프레임들이쌓인다. 메쏘드호출당하나의스택프레임 오퍼랜드스택 (Operand stack) 지역변수 (Local variable) 프레임크기는메쏘드가컴파일될때결정된다.

쓰레드와자바스택 Thread 1 Thread 2 Thread 3 Thread 1 Thread 2 Thread 3 Stack frame Stack frame Stack frame Stack frame Stack frame Stack frame Stack frame Stack frame Thread 3 pc registers Stack frame Java stacks native method stacks

JVM uses stack machine Java Class A extends Object { int i void f(int val) { i = val + 1;} } Bytecode Method void f(int) aload 0 ; object ref this iload 1 ; int val iconst 1 iadd ; add val +1 putfield #4 <Field int i> return refers to const pool JVM Stack frame data area local variables operand stack Return addr, exception info, Const pool res.

메쏘드호출명령어 invokevirtual 객체의가상 (virtual, instance) 메쏘드호출 묵시적매개변수 : this invokeinterface 참조타입이인터페이스일때객체의가상메쏘드호출 묵시적매개변수 : this invokespecial 실체초기화메쏘드, 전용메쏘드, 수퍼클래스메쏘드호출 묵시적매개변수 : this invokestatic 클래스의정적메쏘드 (static method) 호출

메쏘드호출과 this 메쏘드호출의구현 대상객체 (target object) 는 0-번째매개변수로전달 x.m( ); m(x, ); 메쏘드선언의구현 this는 0-번째형식매개변수이름 m( ) { } m(this, ) { }

메쏘드호출과프레임 메쏘드 m 호출전 호출의대상객체 (target object) 주소를스택에넣는다. 실매개변수값들을스택에넣는다. 메쏘드 m 호출후 m을위한새로운프레임을자바스택에넣는다 m의형식매개변수에실매개변수값을복사한다. m 의다른지역변수를초기화한다.

메쏘드호출예 int method1 () {. method2(a, b);. } method1 b a this.. Other local variables of method 2 b a this.. method2 method1 Local variables Local variables 호출전 호출후

invokevirtual int add12and13() { } return addtwo(12, 13); Method int add12and13 0 aload_0 // Push local variable 0 (this) 1 bipush 12 // Push int constant 12 3 bipush 13 // Push int constant 13 5 invokevirtual #4 // Method Example.addtwo(II)I 8 ireturn // Return int on top of operand stack // it is the int result of addtwo()

invokestatic int add12and13() { } return addtwostatic(12, 13); Method int add12and13 0 bipush 12 2 bipush 13 4 invokestatic #3 // Method Example.addTwoStatic(II)I 7 ireturn

메쏘드테이블 (Method Table) 클래스당자료구조 클래스의메쏘드들에대한포인터를갖는테이블 메쏘드호출을위한자료구조 각객체는해당클래스의메쏘드테이블포인터를갖는다. 메쏘드호출구현 객체로부터메쏘드테이블포인터를얻는다. 메쏘드아이디를이용하여해당메쏘드의주소를얻는다. 그주소로점프한다. 상속과재정의 서브클래스는수퍼클래스의메쏘드테이블을상속받는다. 메쏘드가재정의되면해당메쏘드테이블엔트리도갱신된다.

클래스와메쏘드테이블 class A { }; int foo() { } void bar() { } address of foo() address of bar() 0 1 Method table of A class B extends A { int foo() { } float boo() { } }; address of foo() 0 address of bar() 1 address of boo() 2 Method table of B

메쏘드호출예 A a = new A(); a.foo(); Object reference variable new A( ) Objects Data 0 1 Method tables address of foo() address of bar(). a = new B(); a.foo(); a a.bar();. new B( ) Data 0 1 address of foo() address of bar() 2 address of boo()

예외 JVM은비정상적실행상태를탐지한다. Array index out of bounds Load and link error Run out of memory throw 문 예외를발생시킨다. 예외클래스 Exception 클래스의서브클래스로정의 모든예외는예외클래스의객체로 throw된다.

예외처리 예외관리자 예외발생지점의문맥 (context) 를저장한다. 예외를처리할수있는가장가까운 catch 절을찾는다. 발생된예외의타입과예외테이블의 catch 절에선언된타입을비교한다. 찾으면예외 ( 에대한참조 ) 를오퍼랜드스택에넣고 catch 절을실행한다. 찾지못하면해당자바쓰레드를종료한다. 정상적인실행흐름은 catch 절의예외처리기와분리된다.

JVM 의 try-catch void catchone() { try { tryitout(); } catch (TestExc e) { handleexc(e); } } Method void catchone() 0 aload_0 // Beginning of try block 1 invokevirtual #6 // Method Example.tryItOut()V 4 return // End of try block; normal return 5 astore_1 // Store thrown value in local variable 1 6 aload_0 // Push this 7 aload_1 // Push thrown value 8 invokevirtual #5 // Invoke handler method: // Example.handleExc(LTestExc;)V 11 return // Return after handling TestExc Exception table: From To Target Type 0 4 5 Class TestExc

Java Summary Objects have fields and methods alloc on heap, access by pointer, garbage collected Classes Public, Private, Protected, Package (not exactly C++) Can have static (class) members Constructors and finalize methods Inheritance Single inheritance Final classes and methods

Java Summary (II) Subtyping Determined from inheritance hierarchy Class may implement multiple interfaces Virtual machine Load bytecode for classes at run time Verifier checks bytecode Interpreter also makes run-time checks type casts array bounds Portability and security are main considerations

Some Highlights Dynamic lookup Different bytecodes for by-class, by-interface Search vtable + Bytecode rewriting or caching Subtyping Interfaces instead of multiple inheritance Awkward treatment of array subtyping (my opinion) Bytecode-based JVM Bytcode verifier Security: security manager, stack inspection

Links Enhancements in JDK 5 http://java.sun.com/j2se/1.5.0/docs/guide/language/index.html J2SE 5.0 in a Nutshell http://java.sun.com/developer/technicalarticles/releases/j2se15/ Generics http://www.langer.camelot.de/resources/links/javagenerics.ht m