Java의 개체 및 클래스
Java 개체와 클래스에 대해 알아보겠습니다. 객체 지향 프로그래밍 기술에서는 객체와 클래스를 사용하여 프로그램을 설계합니다.
Java의 개체는 논리적 개체일 뿐 아니라 물리적 개체이기도 하지만, Java의 클래스는 논리적 개체일 뿐입니다.
Java에서 개체란
오브젝트를 Java로 지정합니다.
상태 및 동작이 있는 개체를 의자, 자전거, 마커, 펜, 테이블, 자동차 등과 같은 개체라고 합니다. 물리적 또는 논리적(유형 및 무형)일 수 있습니다. 무형의 물체의 예는 은행 시스템입니다.
개체에는 세 가지 특성이 있습니다.
state : 개체의 데이터(값)를 나타냅니다.
behavior : 입금, 인출 등과 같은 개체의 동작(기능)을 나타냅니다.
Identity : 개체 ID는 일반적으로 고유 ID를 통해 구현됩니다. 외부 사용자가 ID 값을 볼 수 없습니다. 그러나 JVM에서 내부적으로 각 개체를 고유하게 식별하는 데 사용됩니다.
예를 들어, 펜은 객체입니다. 그것의 이름은 레이놀즈입니다; 색깔은 그것의 상태로 알려진 하얀색입니다. 그것은 글을 쓸 때 사용되기 때문에 글쓰기는 그것의 행동입니다.
개체는 클래스의 인스턴스입니다. 클래스는 개체를 생성하는 데 사용되는 템플릿 또는 Blueprint입니다. 따라서 객체는 클래스의 인스턴스(결과)입니다.
개체 정의:
개체는 실제 개체입니다.
개체는 런타임 엔터티입니다.
개체는 상태와 동작이 있는 개체입니다.
개체는 클래스의 인스턴스입니다.
자바에서 클래스란
클래스는 공통 속성을 가진 개체 그룹입니다. 개체가 생성되는 템플릿 또는 Blueprint입니다. 논리 엔티티입니다. 육체적일 수 없어요.
Java의 클래스는 다음을 포함할 수 있습니다.
- 필드
- 메소드
- 컨스트럭터
- 블록
- 중첩된 클래스 및 인터페이스입니다.
클래스를 선언하는 구문입니다.
class <class_name>{
field;
method;
}
Java의 인스턴스 변수
클래스 내에서 생성되지만 메서드 외부에 있는 변수를 인스턴스 변수라고 합니다. 인스턴스 변수가 컴파일 시 메모리를 가져오지 않습니다. 개체 또는 인스턴스가 생성될 때 런타임에 메모리를 가져옵니다. 이것이 인스턴스 변수로 알려진 이유입니다.
Java의 메서드
자바에서 메소드는 객체의 동작을 노출시키기 위해 사용되는 함수와 같습니다.
메소드의 장점
코드 재사용성입니다.
코드 최적화입니다.
Java의 새 키워드
new 키워드는 런타임에 메모리를 할당하는 데 사용됩니다. 모든 개체는 힙 메모리 영역에 메모리를 가져옵니다.
개체 및 클래스 예제: main 내부 클래스
이 예에서는 두 개의 데이터 멤버 ID와 이름을 가진 학생 클래스를 만들었습니다. 새로운 키워드로 학생 클래스의 객체를 만들고 객체의 값을 출력합니다.
여기서는 클래스 내부에 main() 메서드를 만들고 있습니다.
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
개체 및 클래스 예제: main 외부 클래스
실시간 개발에서는 수업을 만들어 다른 수업의 수업을 사용합니다. 그것은 이전의 접근 방식보다 더 나은 접근방식입니다. 다른 클래스에서 main() 메서드를 사용하는 간단한 예를 보겠습니다.
서로 다른 Java 파일 또는 단일 Java 파일에 여러 클래스를 가질 수 있습니다. 단일 Java 원본 파일에 여러 클래스를 정의하는 경우 main() 메서드를 사용하는 클래스 이름으로 파일 이름을 저장하는 것이 좋습니다.
//Java Program to demonstrate having the main method in
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
객체를 초기화하는 3가지 방법
Java에서 객체를 초기화하는 방법에는 세 가지가 있습니다.
- 레퍼런스별
- 메소드별
- 생성자별
1) 개체 및 클래스 예: 참조를 통한 초기화
객체를 초기화한다는 것은 객체에 데이터를 저장하는 것을 의미합니다. 참조 변수를 통해 개체를 초기화할 간단한 예를 보겠습니다.
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
//printing members with a white space
}
}
또한 참조 변수를 통해 여러 개체를 생성하고 그 안에 정보를 저장할 수 있습니다.
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
2) 개체 및 클래스 예: 메서드를 통한 초기화
이 예에서는 Student 클래스의 두 개체를 만들고 insertRecord 메서드를 호출하여 이 개체의 값을 초기화합니다. 여기서는 displayInformation() 메서드를 호출하여 개체의 상태(데이터)를 표시합니다.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
위 그림에서 볼 수 있듯이 개체는 힙 메모리 영역에서 메모리를 가져옵니다. 참조 변수는 힙 메모리 영역에 할당된 개체를 나타냅니다. 여기서 s1과 s2는 모두 메모리에 할당된 개체를 참조하는 참조 변수입니다.
3) 개체 및 클래스 예: 생성자를 통해 초기화
나중에 자바의 컨스트럭터에 대해 배울 것입니다.
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
개체 및 클래스 예: 직사각형
직사각형 클래스의 레코드를 유지하는 다른 예가 있습니다.
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Java에서 개체를 만드는 다른 방법
java에서 개체를 만드는 방법은 여러 가지가 있습니다. 다음과 같습니다.
- 새 키워드로 지정합니다.
- newInstance() 메서드
- clone() 방법
- 역직렬화
- factory method
익명 개체
익명성은 단순히 이름 없는 것을 의미합니다. 참조가 없는 개체를 익명 개체라고 합니다. 개체 생성 시에만 사용할 수 있습니다.
개체를 한 번만 사용해야 하는 경우 익명 개체가 좋은 방법입니다. 예를 들어 다음과 같습니다.
new Calculation();//anonymous object
참조를 통해 메서드를 호출합니다.
Calculation c=new Calculation();
c.fact(5);
익명 개체를 통해 메서드를 호출합니다.
new Calculation().fact(5);
Java에서 익명 객체의 전체 예를 살펴보겠습니다.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}
한 유형별로만 여러 개체를 생성
원시적인 경우처럼 한 가지 유형으로 여러 개체를 만들 수 있습니다.
기본 변수를 초기화합니다.
int a=10, b=20;
기준 변수를 초기화합니다.
Rectangle r1=new Rectangle(), r2=new Rectangle();
//creating two objects
예를 들어 보겠습니다.
//Java Program to illustrate the use of Rectangle class which
//has length and width data members
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
//Java Program to demonstrate the working of a banking-system
//where we deposit and withdraw amount from our account.
//Creating an Account class which has deposit() and withdraw() methods
class Account{
int acc_no;
String name;
float amount;
//Method to initialize object
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt;
}
//deposit method
void deposit(float amt){
amount=amount+amt;
System.out.println(amt+" deposited");
}
//withdraw method
void withdraw(float amt){
if(amount<amt){
System.out.println("Insufficient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}
//Creating a test class to deposit and withdraw amount
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}
}