An object is an instance of a class.

Download Report

Transcript An object is an instance of a class.

JAVA
Chapter 3
Objects and Classes
Object & Class
• Object
– 구성 요소
• Internal state ( field )
• Functionality ( method )
– Class 에 의해 정의 된다.
• Class
– Data type 의 한 종류
– C 에서 Structure 의 기능을 확장
– 멤버들의 접근 권한을 설정할 수 있다.
An object is an instance of a class.
Object-Oriented Programming
• 객체들 간의 메시지를 주고 받는 형식
• 목표 : code reuse
Atomicity
객체는 하나의 기본 단위로 생각한다.
Information hiding 불필요한 정보는 볼 필요도 없고
보여주지도 않는다.
Encapsulation
데이터와 그에 관련된 연산을 묶어 놓는다.
Generic code
데이터 타입을 신경 쓰지 않고 동일한 구현이 가능
Inheritance
어떤 클래스의 기능을 확장하는 방법
Polymorphism
실행시간에 실제 선택될 객체 또는
불려질 메소드가 결정되는 기능
Access modifier
• public
– 모든 객체에서 사용할 수 있다.
– ‘.’ operator 로 접근한다.
• private
– 그 객체의 멤버 메소드만이 사용할 수 있다.
• Etc
– protected, package
All data members should be private
Example
// IntCell class
// int read()
// void write(int x)
returns the stored value
x is stored
public class IntCell
{
// public methods
public int read() { return storedValue; }
public void write(int x) { storedValue = x; }
}
// private internal data representation
private int storedValue;
Example
public class TestIntCell {
public static void main(String[] args) {
IntCell m = new IntCell();
m.write(5);
System.out.println(
“Cell contents: ” + m.read() );
// m.storedValue = 0;
illegal
// because storedValue is a private member
}
}
Javadoc
• 객체를 사용하기 위해서는 구현은 알 필요가 없지만, 스펙(인터페이
스)은 알아야만 한다.
• C++ : header file( .h)와 source file( .cpp)를 분리
• Java : javadoc에 의해 소스코드가 HTML파일로 자동으로 문서화 된
다.
• /** */ 주석은 추가적인 내용을 넣는데 사용
• @author, @param, @return, @exception
Example
/**
* A class for simulating an integer memory cell
* @author Mark A. Weiss
*/
public class IntCell {
/**
* Get the stored value.
* @return the stored value.
*/
public int read() {
return storedValue;
}
/**
* Store a value.
* @param x the number to store.
*/
public void write( int x ) {
storedValue = x;
}
private int storedValue;
}
Example
this keyword
• 현재 자신에 대한 레퍼런스
– 다른 객체에게 자신의 레퍼런스를 전달
– 받아들인 객체가 자신인지 비교
• constructor를 부르기 위한 this
– 다른 파라메터를 갖는 컨스트럭터를 부를때
– 생성자의 처음에 위치해야 한다.
instanceof
• 레퍼런스 변수가 가르키는 객체가 특정 Class의 인스턴스인
지 평가
exp instanceof ClassName
exp 가 ClassName 의 인스턴스 이면 true 를 반환
Constructor
• 객체를 초기화 한다.
• 오버로딩이 가능하다.
• 클래스와 이름과 같고, 리턴 타입이 없다.
• Default Constructor
– 생성자가 없는 경우 저절로 만들어 진다.
– 모든 필드를 0과 null로 초기화
Example
public class Circle {
public double x, y, r;
// center and radius
public Circle( double x, double y, double r) {
this.x = x; this.y = y; this.r = r;
}
public Circle(double r) {x = 0.0; y = 0.0; this.r = r; }
public Circle(Circle c) {x = c.x; y = c.y; r = c.r;}
public Circle( ) { x = 0.0; y = 0.0; r = 0.0;
//this(0.0, 0.0, 0.0);
}
public double circumference() { return 2*3.14*r; }
public double area() { return 3.14*r*r; }
}
Mutator/Accessor
• Mutator
– 객체 내부의 필드 값을 변화시키는 메소드
• Accessor
– 객체 내부의 필드 값을 알아내는 메소드
• 관습
– 특정 한 필드에 대한 Mutator/Accessor는 set과 get을 붙인다. ex> setMonth,
getMonth
Special methods
• toString
– public String toString()
– 객체의 내부 상태를 표현하기 위해 사용
– 출력에 적합한 스트링
• equals
– public boolean equals( Object rhs )
– 다른 객체와 동일성을 비교하기 위해 사용.
Example
public class Date {
private
int month, day, year;
// ….constructor here ….
public String toString( ) {
return month + “/” + day + “/” + year;
}
}
public boolean equals( Object rhs ) {
// Return true if two equal values
if(! (rhs instanceof Date) )
return false;
Date rhDate = (Date) rhs;
return rhDate.month == month && rhDate.day == day
&& rhDate.year == year;
}
‘static’ field
• 오직 하나의 인스턴스만이 생성된다.
• 그 클래스의 모든 객체에 공유된다.
• class vars는 class가 처음 로드될때 초기화
• 객체.필드 로 액세스 가능하고
• public인 경우에는 클래스.필드로도 가능하다.
•
•
•
•
•
•
‘static’
method
class method라고도 불린다.
객체가 생성되지 않고도 사용될 수 있는 메소드.
생성된 모든 객체는 공유한다.
ex: main, Integer.parseInt, Math.sin ...
class method는 instance뿐만 아니라 class를 통해 invoke된다.
static 메소드는 전역 함수와 같은 역할
Example
class Ticket{
public Ticket(){
System.out.println("Calling constructor");
serialNumber = ++ticketCount;
}
public int getSerial(){
return serialNumber;
}
public String toString(){
return "Ticket #" + getSerial();
}
public static int getTicketCount(){
return ticketCount;
}
private int serialNumber;
private static int ticketCount = 0;
}
Example
class TestTicket{
public static void main(String [] args){
Ticket t1;
Ticket t2;
System.out.println("Ticket count is" +
Ticket.getTicketCount());
t1 = new Ticket();
t2 = new Ticket();
System.out.println("Ticket count is" +
Ticket.getTicketCount());
System.out.println(t1.getSerial());
System.out.println(t2.getSerial());
}
}
static initializer
• static field를 초기화 하기 위해 static field 선언 바로 다음
에
• static block을 만들어서 초기화하는 구문을 넣을 수 있다.
Example
public class Circle {
static private double sines[] = new double[1000];
static private double cosines[] = new double[1000];
// Here’s a static initializer method that fills them in
static {
double x, delta_x;
delta_x = (Circle.PI/2)/(1000 - 1);
for(int i = 0, x = 0.0; I < 1000; I++, x += delta_x){
sines[I] = Math.sin(x);
cosines[I] = Math.cos(x);
}
} //…. The rest of the class omitted…..
}
Constants
• ‘static final’을 이용하여 선언
public class Circle {
public static final double PI = 3.141592;
public double x, y, r;
// .. Etc….
}
• ‘final’이 사용되면 이 변수는 값이 변하지 않을 것이란 걸
의미
Example
public class Circle{
public double x, y, r;
// an instance method. Return the bigger of two circles
public Circle bigger(Circle c) {
if(c.r > r) return c; else return this;
}
// a static method. Return the bigger of two circles
public static Circle bigger(Circle a, Circle b) {
if(a.r > b.r) return a; else return b;
}
}
//…other methods are omitted here…
‘static’ method
• class method invoke시
Circle a = new Circle(2.0);
Circle a = new Circle(3.0);
Circle c = Circle.bigger(a,b);
• instance method invoke시
Circle c = a.bigger(b);
‘main’ method
• 모든 클래스 마다 있을 수 있다.
• 그 클래스를 테스트 하는데 쓰일 수 있다.
Packages
• 유사한 클래스들의 모음
– Java.util 패키지의 Date 클래스를 쓰려면 다른 패키지의 Date 클래스와의
name conflict를 방지하기 위해 클래스 앞에 패키지 이름을 써줘야 한다.
– java.util.Date today = new java.util.Date();
ex) java.applet
java.awt : window toolkit, which is used for GUI
java.io : used for I/O, various stream classes
java.lang : Integer, Math, String, System, etc..
java.util : Date, Random, StringTokenizer, etc..
default
import
• 자주 쓰이는 클래스에 패키지 이름을 계속 쓰는걸 방지하기 위해
• 형식
– import PackageName.ClassName;
– import PackageName.*;
• 장점
– typing이 절약된다.
• 단점
– 특정 클래스가 어느 패키지 인지 알 수 없다.
– 다른 패키지에 같은 이름의 클래스가 있는경우 풀네임을 써줘야 한다.
package keyword
• Class
– 소스코드에서 클래스 선언 앞에 적어준다.
– 해당 클래스가 속한 패키지를 나타낸다.
– 소스코드를 패키지 이름의 디렉토리에 배치한다.
• Method/Field
– public, private등을 선언하지 않은 메소드, 필드, 클래스의 디폴드 access 지정
자
– 같은 패키지내의 클래스들은 사용할 수 있다.
CLASSPATH
• 자바가 컴파일 할 때 패키지를 찾게 되는 디렉토리들을 명시
• P 패키지에 속한 클래스는 반드시 CLASSPATH에 명시된 디렉토리 중
하나에서 P 라는 서브디렉토리에 존재 해야 한다.
• 현재 디렉토리(.) 는 항상 CLASSPATH 변수에 있어야 한다.
SET CLASSPATH = .;C:\café\java\lib\
(for Win95)
setenv CLASSPATH = .:$HOME/java/:usr/java/lib (UNIX)