11.1 객체, 클래스, 및 메쏘드
(Objects, Classes, and Methods)
동기
n Simulation of real-world objects in programs
n An object
n Storage and state
객체
l An object = data(instance variables) + operations(methods)
- An object has storage and state (values in instance variables)
- An object can be accessed and modified via only its methods
l For example, a bank account
– has an account number and a current balance
– can be deposited into
– can be withdrawn from
클래스
l A defintion for objects
- define data(instance variables)
- define operations(methods)
l A class is a type for objects
- Objects are declared to be of a class type
- An object is an instance of a particular class
l Instantiation
– Creating an object from a class
클래스의 예
l Class in Java
- Definition for instance variables
- Definition for methods
l Class in C++
- Definition for data members and
- Definition for member functions
Java 객체 및 클래스
클래스 정의
l The syntax for defining a class is:
class class-name {
declarations of instance variables
constructors
methods
}
l The variables, constructors, and methods of a class are generically called members of the class
클래스 정의: 예
class Account {
int account_number;
double balance;
Account (int account, double initial) {
account_number = account;
balance = initial;
} // constructor Account
void deposit (double amount) {
balance = balance + amount;
} // method deposit
} // class Account
객체 생성
l The new operator creates an object from a class:
Account saving = new Account ();
l saving is a variable that refers to an object created from the Account class
l It is initialized to the object created by the new operator
l The newly created object is set up by a call to a constructor of the class
클래스 및 객체
l A class defines the data types for an object, but a class does not store data values
l Each object has its own unique data space(memory)
l Instance variables
– The variables defined in a class .
– Each instance(object) of the class has its own.
클래스 및 객체
생성자(Constructors)
l A constructor:
– is a special method that is used to set up a newly created object
– often sets the initial values of variables
– has the same name as the class
– does not return a value
– has no return type, not even void
l The programmer does not have to define a constructor for a class
생성자(Constructors)
l For example, the Account constructor could be set up to take a parameter specifying its initial balance:
Account toms_savings = new Account (1,125.89);
객체 참조 변수
l The declaration of the object reference variable
l The creation of the object
Account toms_savings;
toms_savings = new Account (1, 125.89);
객체 참조 변수
l An object reference holds the memory address of an object
Chess_Piece bishop1 = new Chess_Piece();
l All interaction with an object occurs through a reference variable
l References have an effect on actions such as assignment
배정문(Assignment)
l The act of assignment takes a copy of a value and stores it in a variable
l For primitive types:
num2 = num1;
객체 참조 변수 배정
l For object references, the value of the memory location is copied:
bishop2 = bishop1;
이명(Alias)
l Two or more references are called aliases if
- they refer to the same object
l There is only one copy of the object (and its data),
- but with multiple ways to access it
l Aliases can be useful, but should be managed carefully
l Affecting the object through one reference affects it for all aliases, because they refer to the same object
메쏘드 및 메시지
l Methods are shared among all objects of a class
- All methods in a class have access to all instance variables of the class
l Method call using dot operator:
toms_savings.deposit (35.00);
l Message
- a method call; request to execute a method
메쏘드
l A class contains methods;
- Before defining our own classes, we need method definitions
l We've defined the main method many times
l All methods follow the same syntax:
return-type method-name ( parameter-list ) {
statement-list
}
메쏘드
l A method may contain local declarations
l For example, a method definition:
int third_power (int number) {
int cube;
cube = number * number * number;
return cube;
} // method third_power
메쏘드 제어 흐름
l The main method is invoked by the system when you submit the bytecode to the interpreter
l Each method call returns to the place that called it
매개 변수
• When a parameter is passed, a copy of the value is made and assigned to the formal parameter
• Both primitive types and object references can be passed as parameters
• When an object reference is passed, the formal parameter becomes an alias of the actual parameter
• Usually, we will avoid putting multiple methods in the class that contains the main method
C++ 클래스
n Struct in C
- a type for a collection of data(variables)
n Class in C++
- Extension of struct in C
- to include definitions of operations as well as data
- A type for a collection of
- data members and member functions
- Classes can be used to declare variables and create objects
C++ 객체
l An instance of a class
l s is a variable for objects of stack
Stack s;
C++ 예
class Stack {
public:
char pop();
void push(char);
Stack() { top = 0;}
private:
int top;
char elements[101];
};
char Stack::pop() {
top = top -1;
return elements[top+1];
}
char Stack::push(char c) {
top = top +1;
elements[top] = c;
}
#include <stdio.h>
main() {
Stack s;
s.push('!'); s.push('@'); s.push('#');
printf("%c %c %c \n", s.pop(), s.pop(), s.pop());
}
Members
n Data members
- variables in a class
- top, elements
n Member functions
- functions in a class
- push(), pop(), Stack()
생성자/소멸자(Constructor/Destructor)
l Constructor
- a special member function for initialization
- an automatic execution when object is created
Stack( )
l Destructor
- a special member function for cleanup
- an automatic execution when object is deleted
~Stack( )
Member의 이름
l <class-name>::<member names>
l name(scope) resolution operator ::
l stack::pop()
생성자를 이용한 초기화
struct Complex {
float re;
float im;
Complex(float r, i) { re= r; im=i;}
}
Complex x(1,2);
C++에서 동적 할당
l new T
- create an object of type T
- return a pointer to the newly created object
l delete p
- destroy the object that p points to
객체에 대한 포인터
l A pointer variable p pointing C objects
C *p;
l Using pointer variable
- (*p).info : p->info
- 0 : null pointer, pointing to no object
- this : used within member functions to point to this object itself
생성자/소멸자를 이용한 동적 할당
class Stack {
public:
char pop();
void push(char);
Stack(int);
~Stack();
private:
int top;
int size;
char *elements;
};
Stack::Stack(int n) {
size = n;
elements = new char[size];
top = 0;
}
Stack::~Stack() { delete elements; }
11.2 가시성 조정자(Visibility Modifiers)
캡슐화(Encapsulation)
l An external view of object
- object is an encapsulated entity,
- providing services (i.e. interface to the object)
l An object should be self-governing;
– the object's state should be changed by the methods
– we should make it difficult for another object to "reach in" and alter an object's state
캡슐화(Encapsulation)
l An encapsulated object can be thought of as a black box
l The user, or client, of an object
– can request its services,
– but it should not have to know how the services are accomplished
Java 가시성 조정자(Visbility Modifiers)
l Visibility modifiers를 사용하여 캡슐의 가시성을 조정한다.
l For encapsulation
l Localization of errors
l A user of such a class need only examine the definition of the member function
Java 가시성 조정자
l Java has three visibility modifiers:
– public, private, and protected
l Public members
- can be accessed from anywhere
l Private members
- can only be accessed from inside the class
l Default visibility
- Members without a visibility modifier
- can be accessed by any class in the same package
가시성 조정자
l A general rule
- no object's data should be declared with public visibility
l Public methods
- methods that provide the object's services(interface)
- also called service methods
l Support methods
- assist the service methods;
- they should not be public
CD_Collection.java(1/3)
class Tunes {
// Instantiates an object to monitor the value
// of a collection of musical CDs.
public static void main (String[] args) {
CD_Collection music = new CD_Collection (5, 59.69);
music.add_cds (1, 10.99);
music.add_cds (3, 39.34);
music.add_cds (2, 24.73);
music.print();
music.add_cds (2, 20.82);
music.add_cds (4, 46.90);
music.print();
} // method main
} // class Tunes
CD_Collection.java(2/3)
class CD_Collection {
private int num_cds;
private double value_cds;
// Creates a CD_Collection object with the specified
// initial number of CDs and their total value.
public CD_Collection (int initial_num, double initial_val) {
num_cds = initial_num;
value_cds = initial_val;
} // constructor CD_Collection
// Adds the number of CDs to the collection and updates the value.
public void add_cds (int number, double value) {
num_cds = num_cds + number;
value_cds = value_cds + value;
} // method add_cds
CD_Collection.java(2/3)
// Prints a report on the status of the CD collection.
public void print() {
System.out.println ("***************");
System.out.println ("Number of CDs: " + num_cds);
System.out.println ("Value of collection: $" + value_cds);
System.out.println ("Average cost per CD: $" +average_cost());
} // method print
// Computes and returns the average cost of a CD in this collection.
private double average_cost () {
return value_cds / num_cds;
} // method average_cost
} // class CD_Collection
C++ 가시성 조정자
n public members
- accesible to outside of the class
n private members
- accesible to the member functions in this class declaration
n protected members
- like private member except for inheritance
- visible through inheritance to derived classes, but no the other code
11.3 메쏘드 중복정의(Method Overloading)
메쏘드 중복정의(Method Overloading)
l Method overloading
– the process of using the same method name for multiple methods
l Signature
– The signature of each overloaded method must be unique
– The signature is based on the number, type, and order of the parameters
l The return type of the method is not part of the signature
Java 메쏘드 중복정의
l The compiler must be able to determine which version of the method is being invoked by analyzing the parameters
l The println method is overloaded:
println (String s), println (int i), println (double d) etc.
l The lines
System.out.println ("The total is:");
System.out.println (total);
invoke different versions of the println method
Java 메쏘드 중복정의
l Constructors are often overloaded to provide multiple ways to set up a new object
Account (int account) {
account_number = account;
balance = 0.0;
} // constructor Account
Account (int account, double initial) {
account_number = account;
balance = initial;
} // constructor Account
C++ 메쏘드 중복정의
class Complex {
float re;
float im;
Complex(float r) { re= r; im=0;}
Complex(float r, i) { re= r; im=i;}
}
Complex y(1);
Complex x(2,5);
2