try
{...}
catch(ExceptionClass1 e)
{...}
...
catch(ExceptionClassN e)
{...}
finally
{
	CodeToBeExecutedInAllCases
}​
throw new ExceptionClassName(SomeString);

Java library softeware는 비정상적인 동작이 발생 했을 때 신호를 보내는 체계를 갖고 있다.

이를 throwing an exception이라고 한다.

예외적인 상황을 처리하는 코드를 제공해야하는데 이를 hadling the exception이라고 한다.

 

try-throw-catch

Java에서는 기본적으로 try-throw-catch를 사용하여 exception handling을 한다.

try에서는 기본적인 코드를 수행한다.

try문에서는 exception을 throw하는 코드를 포함할 수 있다.

throw 되는 경우 이후의 try 문 수행은 중단되고 catch 문으로 넘어가게 된다.

 

throw statement는 함수 호출과 유사하다.

throw new ExceptionClassName(SomeString);

ExceptionClassName 클래스의 객체가 생성된다.

throw 문은 함수를 호출하는 대신 catch block을 불러온다.

 

exception이 throw 되면 catch block 이 실행되기 시작한다.

catch block의 실행을 cathcing the exeception 혹은 handling the exception이라고 한다.

catch(Exception e)
{
	ExceptionHandlingCode
}

e 는 catch block parameter이다.

이 매개변수는 두 가지 역할을 한다.

1.  thrown exception 객체의 유형을 구체화한다.

2. thrown exception 객체를 잡기 위한 이름으로 사용된다.

 

<try-throw-catch 예시>

try
{
	if(men == 0 && women == 0)
		throw new Exception("Lesson is canceled. No students.");
	else if (men ==0)
		throw new Exception("Lesson is canceled. No men. ");
	else if (women ==0)
		throw new Exception("Lesson is canceled. No women.");
        
	if (women >= men)
		System.out.println("Each man must dance with " + women/(double)men + "women.");
	else
		System.out.println("Each woman must dance with " + men/(double)women + "men.");
}
catch(Exception e)
{
	String message = e.getMessage();
	System.out.println(message);
	System.exit(0);
}

 

getMessage Method

...//method code
try
{
	...
	throw new Exception(StringArgument);
	...
}
catch(Exception e)
{
	String message = e.getMessage();
	System.out.println(message);
	System.exit(0);
}

모든 exception은 message를 포함한 String 인스턴스 변수를 갖는다. (주로 exception의 이유를 포함)

StringArgument는 Exception 생성자의 인자이다.

e.getMessage()는 해당 string을 반환하게 된다.

 

Multiple catch Blocks

try block 이후에 다른 유형의 exception을 잡는 catch block이 여러 개 올 수 있다.

catch block이 여러개인 경우 catch block은 순서대로 실행된다.

catch (Exception e)
{...}
catch (NegativeNumberException e)
{...}

위와 같은 경우 NegativeNumberException 이 Exception type에 해당하므로 첫번째 catch문에서 잡히기 때문에 두 번째 catch 문이 사용되지 않게 된다.

올바르게 동작하기 위해서는 두 catch block의 순서를 바꿔야 한다.

 

finally Block

finally block은 exception throw 여부와 관계없이 실행된다.

try
{. . .}
catch(ExceptionClass1 e)
{ . . .}
 . . .
catch(ExceptionClass2 e)
{. . .}
finally
{
	CodeToBeExecutedInAllCases
}

'Development > OOP(Java)' 카테고리의 다른 글

Ch8. Polymorphism and Abstract Classes  (0) 2023.05.08
Ch6. Defining Classes(3)  (0) 2023.04.10
Project1 (Timetable application)  (0) 2023.04.05
Ch3. Flow of Control  (0) 2023.04.04
Ch5. Defining Classes(2)  (0) 2023.04.03

Polymorphism(다형성)

: 하나의 객체나 메서드가 여러 형태로 사용되는 특징

 

Late Binding

- 메서드의 정의와 메서드 실행을 연결시키는 것을 binding이라고 한다.

- 코드가 컴파일 시 binding 되는 경우를 early binding, run time시 binding 되는 것을 late binding 혹은 dynamic binding이라고 한다.

- Java는 late binding을 사용한다. (private, final, static method 는 제외)

 

final Modifier

- final 표기된 method는 오버라이드 될 수 없다. -> base class로 사용될 수 없다!

- final 이 표기된 경우 컴파일러가 early binding을 사용한다.

 

Late Binding with toString

Sale aSale = new Sale("tire gauge", 9.95);
System.out.println(aSale)

toString이 클래스에 정의되어있다면 객체가 System.out.println을 사용하여 올바르게 출력

-> tire gauge Price and total cost = $9.95 (late binding으로 동작)

 

public void println(Object theObject)
{
	System.out.println(theObject.toString());
}

println 메서드는 Sale 클래스가 존재하기 이전에 정의되어있다.

하지만 late binding으로 인해 Object 클래스의 toString이 아닌 Sale 클래스의 toString 메서드가 사용된다.

 

Upcasting and Downcasting

Upcasting : 파생 클래스의 객체가 기초 클래스의 변수에 할당되는 것

Sale saleVariable; //기초 클래스
DiscountSale discountVariable = new DiscountSale("paint", 15,10); //파생 클래스
saleVariable = discountVariable; 	//Upcasting
System.out.println(saleVariable.toString());

-> late binding으로 toString은 Discount 클래스에 정의된 것을 사용한다.

 

Downcasting : 기초클래스의 객체가 파생 클래스의 변수에 할당되는 것

discountVariable = (DiscountSale)saleVariable; // -> run-time error
discountVariable = saleVariable	//-> compiler error
Sale otheSale = (Sale)otherObject; // downcasting

 

clone Method

- 모든 객체는 Object 클래스의 clone 메서드를 상속받는다.

- clone은 기본적으로 얉은복사를 수행한다.

- 클래스가 copy constructor를 갖는 경우 clone 메서드는 copy constructor를 사용할 수 있다.

public Sale clone()
{
	return new Sale(this);
}

public DiscountSale clone()
{
	return new DiscountSale(this);
}

 

Abstract Classes(추상 클래스)

- 추상메서드를 선언하고 상속을 통해 자식클래스에서 메서드를 완성하도록 하는 클래스

- 추상메서드를 포함하는 클래스를 추상클래스라고 한다.

 

Abstract Method(추상 메서드)

- abstract 수식자를 사용한다.

- private로 사용할 수 없다.

- head 부분만 존재하고 body부분은 갖지 않는다.

public abstract class Employee
{
	private instanceVariable;
	public abstract double getPay();
}

 

'Development > OOP(Java)' 카테고리의 다른 글

Ch9. Exception Handling  (0) 2023.05.19
Ch6. Defining Classes(3)  (0) 2023.04.10
Project1 (Timetable application)  (0) 2023.04.05
Ch3. Flow of Control  (0) 2023.04.04
Ch5. Defining Classes(2)  (0) 2023.04.03

Class Parameters

Java 의 parameter 는 call-by-value parameter 이다.

 - parameter 는 local 변수로 인자의 값과 같다.

 - 즉, parameter 의 값은 인자의 값을 변경할 수 없다.

Class type의 parameter 는 primitive type과 다르게 call-by-reference로 동작한다.

 

call-by-value : 값을 인자로 전달하는 방식

call-by-reference : 값을 전달하는 대신 주소값을 전달하는 방식

 

Class type의 parameter 에 연결된 값은 reference(memory 주소) 이다.

 - 매개변수는 인자의 다른 이름이 된다.

 - 여전히 call-by-value 이므로 class type parameter 자체에 대한 수정은 해당 인자를 변경하지 않는다.

 

<예시>

println은 String class를 인자로 가질 수 있다. anObject의 경우 string이 아닌 객체이지만 toString()을 자동으로 호출하여 string class type 인자로 가지도록 한다.

ToyClass의 changer를 호출하여 anObject 값을 Hot Shot 42 로 변경한다.

이때 anObject 는 객체에 대한 주소값을 갖고 있다.  changer 함수를 호출하는 경우 객체의 정보가 변경되는 것이다.

 

Differences Between Primitive and Class-Type Parameters

primitive type의 변수가 메서드에서 인자로 사용될 때 원래 값으로 변경될 수 없다.

하지만 인자로 사용되는 class type의 instance 변수값은 변경할 수 있다.

 

<예시>

1) object1.makeEqual(object2) ;  -> object2 내용이 object1 내용으로 수정된다. 즉, class type의 instance 변수값이 변경

2) object1.tryToMakeEqual(aNumber); -> aNumber 변수값 자체가 변경되지 않음, 42 값 그대로 갖고 있음

Use of = and == with Variables of a Class Type

class type의 변수와 사용하는 할당 연산자 (=) 는 동일한 객체의 이름을 지정하는 두 개의 변수를 생성한다.

 equality 검증 (==) 은 class type 변수에서 다르게 동작한다.

 - "==" 는 두 class type 변수가 같은 메모리 주소를 가리키는지 확인한다.

 - instance 변수의 값이 같은지 확인x

 - instance 변수 값이 같은 서로 다른 두 객체는 같지 않음을 확인 할 수 있다.

 

The Constant null

null 은 special constant 로 class 변수에 대입 가능하다. 값이 없다는 의미로 가리키는 객체가 없음을 의미한다. null 자체는 객체가 아니다.

-> equals를 사용하지 않고 ==, != 를 사용하여 null 값을 갖는지 확인한다.

 

The new Operator and Anonymous Objects

new operator 는 생성자를 호출하여 객체를 초기화한 후 객체가 생성된 위치의 메모리 주소를 반환해준다.

ex) ToyClass variable1 = new ToyClass("Joe", 42);

 

객체가 메서드의 인자로 임시적으로만 사용되는 경우가 있다. 이 경우 객체는 변수로 할당 될 필요가 없음

-> 이러한 객체를 anonymous object 라고 한다. 

 

Using and Misusing References

프로그램 작성 시 private  인스턴스 변수는 private 하게 보존해주는 것이 중요하다. 

primitive type 인스턴스 변수의 경우 private modifier 사용으로 privacy leaks를 막을 수 있다.

하지만 class type의 경우 private modifier 사용으로만으로는 privacy leaks를 막을 수 없다.

 

ex) 각 변수에 private 를 선언해준다

Copy Constructors

copy constructors 는 모든 인스턴스 변수를 수동으로 복사할 필요 없이 기존 객체의 복사본인 새 객체를 만드는 방법이다.

인스턴스 변수가 많은 복잡한 객체를 처리하는 경우 유용하게 사용 할 수 있다.

즉, 따로 객체를 만들어서 copy 하는 방식으로 기존 객체의 데이터는 변하지 않고 안전하게 복사 할 수 있다.

<예시>

 

Privacy Leaks

중요한 데이터가 외부 클래스에 노출되어 엑세스하거나 수정할 수 있는 경우 privacy leaks 문제가 생긴다.

다음 예시에서 getBirthDate() 메서드는 다른 클래스가 Date 객체를 직접 수정할 수 있도록하는 참조를 반환한다.

이 경우 Date 객체가 잘못된 값으로 수정될 수 있어 위험이 발생한다.

이런 문제를 방지하기 위해 실제 참조가 아니라 복사본을 반환하도록 하여 안전성을 보장한다. -> copy constructor 사용

 

<예시>

 

Mutable and Immutable Classes

Mutable class : 생성 후 수정이 가능한 객체

Immutable class : 생성 후 바꿀 수 없는 객체 -> string class는 immutable class

 

Deep Copy Versus Shallow Copy

Deep Copy 의 경우 모든 속성을 포함하는 새 객체를 만들고 참조하는 모든 속성을 복사한다.

즉, 자체 메모리 공간을 가진 새 객체를 생성하여 변경사항은 원래 객체에 영향을 주지 않는다.

 

Shallow Copy의 경우 새 객체를 생성하지만 참조하는 속성은 복사하지 않는다. 따라서 원래 객체와 동일한 속성의 참조를 포함한다.

따라서 새로운 메모리 공간을 생성하는 것이 아니기에 복사본의 변경사항은 원래 객체에 영향을 주어 보안 문제가 발생 할 수 있다.

 

Packages

Java는 라이브러리와 클래스로 구성된 packages 를 사용한다.

디렉터리, 폴더로 관리하여 import statement를 사용하여 프로그램 작성 시 사용할 수 있도록 한다.

 

ex) import java.util. * ; -> 해당 패키지의 모든 것을 import 한다

=> 컴파일 할 때 필요한 부분만 사용하므로 오버헤드 발생에 대한 문제를 고려하지 않아도 된다.

 

java.lang 은 기본적인 클래스를 포함한다. (Math, String, Wrapper class 등)

 

패키지 이름은 패키지 클래스를 포함하는 디렉토리 또는 하위 디렉토리의 경로 이름이다.

Java는 패키지의 디렉토리를 찾기 위해 패키지 이름과 CLASSPATH 환경변수 두 가지를 사용한다.

 

 

The Default Package

현재 디렉터리의 모든 클래스는 이름없는 패키지인 default package 라고 한다.

현재 디렉터리(.) 는 CLASSPATH 변수의 일부로 default package 의 모든 클래스는 자동적으로 프로그램에서 사용가능하다.

 

Name Clashes

다른 개발자들이 작성하는 경우 같은 이름의 클래스를 사용하는 경우가 있다.

이러한 경우 fully qualified name 을 사용하여 Name Clashes 문제를 해결 할 수 있다.

qualified name 을 사용하는 경우 class를 import 할 필요가 없다.

 

 

'Development > OOP(Java)' 카테고리의 다른 글

Ch9. Exception Handling  (0) 2023.05.19
Ch8. Polymorphism and Abstract Classes  (0) 2023.05.08
Project1 (Timetable application)  (0) 2023.04.05
Ch3. Flow of Control  (0) 2023.04.04
Ch5. Defining Classes(2)  (0) 2023.04.03

과제 주제 : Timetable Application 구현

 

과제 조건

-Course class

먼저 Course class에 필요한 변수 (이름,교수,강의실번호,가능여부)를 선언하고 생성자를 초기화해준다.

- Timetable Class

 

- TimeTableAPP Class

- 크게 주어진 세 개의 클래스를 기반으로 timetable application을 구현한다.

- course class 는 시간표에 포함될 내용인 수업에 대한 속성과 메서드를 제공하는 클래스이다.

- timetable class는 강의 일정을 관리하는 메서드를 포함하는 클래스이다.

- timetableapp class는 main 함수를 포함하여 수업일정을 추가,확인 및 관리할 수 있도록 작성한 application 구현 클래스이다.

 

Implement

<Course Class>

package assignment;

import assignment.Course;

public class Course {		//강의 속성에 사용하는 변수 선언
	public String name;
	public String professor;
	public String roomNumber;
	public boolean isValid;

	//각각의 생성자
	public Course(String name, String tutor, String room) {
		this.name = name;
		this.professor = tutor;
		this.roomNumber = room;
	}

	public Course(String name) {
		this.name = name;
	}

	public Course(Course copy) {
		this.name = copy.name;
		this.professor = copy.professor;
		this.roomNumber = copy.roomNumber;
		this.isValid = copy.isValid;
	}

	//get 함수
	public String getName() {
		return name;
	}
	
	public String getProfessor() {
		return professor;
	}
	public String getRoomNumber() {
		return roomNumber;
	}

	//set함수
	public void setName(String name) {
		this.name = name;
	}
	public void setProfessor(String professor) {
		this.professor = professor;
	}
	public void setRoomNumber(String roomNumber) {
		this.roomNumber = roomNumber;
	}

	//동일한 강의인지 확인하는 메서드
	public boolean equals(Course s) {
        if (this.name.equals(s.name) && this.professor.equals(s.professor) && this.roomNumber.equals(s.roomNumber)) {
            return true;
        }
        return false;
    }	

	// 강의명을 반환해주는 메서드
	public String toString() {
		return name;	
	}

	// 강의명, 교수명, 강의실 정보를 반환해주는 메서드
	public String getDetails() {
		return "\nName : " + name + "\n" + "Tutor : " + professor +  "\n" + "Room : " + roomNumber + "\n";
		
	}
}

<TimeTable Class>

package assignment;

import java.util.Calendar;
import java.util.Scanner;

import assignment.Course;


public class TimeTable {
	Course[][] timeTable = new Course[5][10];
	
    //열거형 type 으로 요일 상수 정의
	public enum DAYS {
		MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
	}

	//2차원 배열로 시간표 생성
	public TimeTable() {
		timeTable = new Course[DAYS.values().length][10];
		initialize();
		
	}
	//시간표 초기화 (점심,저녁시간 고정값으로 설정)
	private void initialize() {
        for (int i = 0; i < timeTable.length; i++) {
            for (int j = 0; j < timeTable[i].length; j++) {
                if (j == 3) {
                    timeTable[i][j] = new Course("  LUNCH", "-", "-");
                } else if (j == 7) {
                    timeTable[i][j] = new Course(" DINNER", "-", "-");
                } else {
                    timeTable[i][j] = new Course("  ----", "-", "-");
                }
            }
        }
	}
	
    //요일과 period를 받아 시간표에 입력하는 메서드
	public String getSchedule(String day, int period) {

        int dayIndex = DAYS.valueOf(day).ordinal();
        Course course = timeTable[dayIndex][period-1];
        return "At that time you have: " + course.getDetails();
	}
    
	// 강의 속성 정보를 받아 가능여부 판단
	public boolean setSchedule(String day, int period, String name, String tutor, String room) {
        if (period == 3 || period == 7) {
            return false;
        }
        int dayIndex = DAYS.valueOf(day).ordinal();
        timeTable[dayIndex][period-1].setName(name);
        timeTable[dayIndex][period-1].setProfessor(tutor);
        timeTable[dayIndex][period-1].setRoomNumber(room);
        return true;
	}

	// 시간표 format 출력
	public String toString() {		//timetable 형태를 return
            StringBuilder sb = new StringBuilder();
            sb.append("\tMONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY\n");
            for (int i = 0; i < timeTable[0].length; i++) {
                sb.append((i + 1) + "\t");
                for (int j = 0; j < timeTable.length; j++) {
                    sb.append(timeTable[j][i].getName() + "\t");
                }
                sb.append("\n");
            }
            return sb.toString();
        }
        
	//요일을 입력받아 해당 요일의 시간표를 반환하는 메서드
	public String oneDaySchedule(String day) {			
        int dayIndex = DAYS.valueOf(day).ordinal();
        String result = DAYS.values()[dayIndex] + "\n";
        for (int j = 0; j < timeTable[dayIndex].length; j++) {
            result += timeTable[dayIndex][j].getDetails() + "\t";
        }
        result += "\n";
        return result;
	}
	
    //강의명을 입력 받아 요일을 반환하는 메서드
	public String subjectSchedule(String sub) {		
        String result = "";
        for (int i = 0; i < timeTable.length; i++) {
            for (int j = 0; j < timeTable[i].length; j++) {
                if (timeTable[i][j].getName().equals(sub)) {
                    result += "Subject: " + timeTable[i][j].getName() + "\n" + "Day: "+ DAYS.values()[i] + "\n" + "Lecture: "+ (j+1) + "\n" + "Professor: " + timeTable[i][j].getProfessor() + "\n" + "Room No: " + timeTable[i][j].getRoomNumber();
                }
            }
        }
        return result;
	}
	
    //날짜를 입력받아 calender class 객체에 저장후 객체 반환(calender class 사용)
	public Calendar setInputDate(String date) {			
	
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(4, 6)) - 1;
        int day = Integer.parseInt(date.substring(6));
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        return cal;
    
	}
}

<TimeTableApp Class>

package assignment;

import java.util.Calendar;
import java.util.Scanner;

public class TimeTableApp {
	public static void main(String[] args) {

		Scanner keyboard = new Scanner(System.in);
		String[] weeks = { "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" };
		Calendar cal = Calendar.getInstance();
		TimeTable timeTable = new TimeTable();
		int enter, period;
		String name, day, tutorName, roomName, sub, str,date;
		boolean check;
		boolean when = true;
		do {
			System.out.println(timeTable.toString());
			System.out.println("===============Main Menu================");
			System.out.println("(1) Add a class to my time table");
			System.out.println("(2) View the class at a specific period");
			System.out.println("(3) View schedule of a specific class");
			System.out.println("(4) TimeTable corresponding to input date");
			System.out.println("(5) Exit the program");
			System.out.println("===============Main Menu================");
			enter = keyboard.nextInt();
			switch (enter) {
			case 1: {		//강의 정보를 입력받아서 시간표에 저장
				System.out.println("Please enter the day to add the class");
				day = keyboard.next();
				day = day.toUpperCase();
				System.out.println("Please enter the period to add the class");
				period = keyboard.nextInt();
				System.out.println("Please enter the name of the class");
				name = keyboard.next();
				System.out.println("Please enter the name of the tutor");
				tutorName = keyboard.next();
				System.out.println("Please enter the name of the room ");
				roomName = keyboard.next();

				check = timeTable.setSchedule(day, period, name, tutorName, roomName);
				if (check == true)
					System.out.println("Class successfully added");
				else
					System.out.println("Class was NOT successfully added");
				break;

			}
			case 2: {		// 요일과 교시를 입력받아 해당 시간의 강의 속성을 출력
				System.out.println("Please enter the day of the class");
				day = keyboard.next();
				day = day.toUpperCase();
				System.out.println("Please enter the peroid of the class");
				period = keyboard.nextInt();
				System.out.println(timeTable.getSchedule(day.toString(), period));
				break;

			}
			case 3: {		// 강의명을 입력받아 해당 강의 정보를 출력
				System.out.println("Please enter the class name");
				sub = keyboard.next();
				str = timeTable.subjectSchedule(sub);
				
				if (str.isEmpty()) {
					System.out.println("There are no class");
					break;
				} else {
					System.out.println(str);
				}
				break;
			}
			case 4: {		//날짜를 입력받아 해당하는 요일의 시간표를 출력
				System.out.println("Enter the date:");
				date = keyboard.next();
				cal = timeTable.setInputDate(date);
				
				if (cal.get(Calendar.DAY_OF_WEEK) - 1 == 0 || cal.get(Calendar.DAY_OF_WEEK) - 1 == 6) {
					System.out.println("There are no schedule");
					break;
				} else {
					System.out.println(timeTable.oneDaySchedule(weeks[cal.get(Calendar.DAY_OF_WEEK) - 1]));
				}

				break;

			}
			case 5: {		// 프로그램 종료
				when = false;
				break;
			}
			default:
				System.out.println("Try again");
			}
		} while (when);

	}

}

 

Result

1. Case1 : 강의 속성을 입력받아 시간표에 저장

 

2. Case2 : 요일과 교시를 입력받아 해당 강의 속성 출력

3. Case3 : 강의명을 입력받아 해당 강의 정보 출력

4. Case4 : 날짜를 입력받아 해당날짜의 시간표 출력 (2023.04.07은 금요일 -> 금공강^^)

5. Case5 : 프로그램 종료

'Development > OOP(Java)' 카테고리의 다른 글

Ch8. Polymorphism and Abstract Classes  (0) 2023.05.08
Ch6. Defining Classes(3)  (0) 2023.04.10
Ch3. Flow of Control  (0) 2023.04.04
Ch5. Defining Classes(2)  (0) 2023.04.03
Ch2. Console Input and Output  (0) 2023.04.01

Flow of Control (제어 흐름)

branching 과 looping 두가지를 참고할 수 있다.

branching 과 looping은 boolean expressions 로 control 된다.

Branching mechanism :

-if , else if, else

-switch

Compound Statements

→ 명령어를 여러 줄 쓰는 경우 braces({ }) 기호 사용

else는 생략 가능

The Conditional Operator

if (n1 > n2) max = n1;
else         max = n2;

max = (n1 > n2) ? n1 : n2;   (conditional operator)

Boolean Expressions

  • and - && , or - || , not - !

-&, | 로도 사용 가능

*Short-Circuit

:&&의 경우 처음이 false이면 반드시 false이므로 이후 계산 수행x, ||의 경우 처음이 true이면 반드시 true이므로 이후 계산 수행x

→ 프로그램 실행 시간을 줄여줌(효율적) , 런타임 에러를 줄여준다.

ex1)

→ if, else if, else 를 사용하여 입력받은 값에 따른 tax 값을 계산해서 출력하는 프로그램

ex2)

→ switch 문을 사용하여 각각의 경우에 따른 출력값을 출력

-case2,3 처럼 비어 있는 경우 다음으로 넘어가서 case 4의 내용을 출력

-default는 해당 값이 없는 경우에 대해 출력

Using == with Strings

equality comparison을 위해 (==) 연산자를 사용한다.

이때, primitive type에서는 두 값을 비교하게 된다.

하지만 String class의 경우(==)연산자는 값을 비교하는 것이 아니라 같은 메모리 location을 가리키는 것인지 확인하는 용도로 사용된다.

따라서, String class의 값을 비교하기 위해서는 equals, eqaulsIgnoreCase와 같은 method를 사용하여 확인해야 한다.

Loops

-while, do-while, for statements 가 있다.

-loop에서 반복되는 부분의 코드를 body라고 한다.

-body 중에서 반복하는 부분을 iteration이라고 한다.

*while과 do-while의 차이

→while은 조건을 먼저 확인 후 body를 실행한다. 하지만, do-while의 경우 body를 먼저 실행한 뒤 조건을 evaluation한다. 따라서 do-while의 경우 반드시 1번은 body문이 실행된다.

ex3)

package chapter3;

public class chapter3_3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int countDown;
		
		System.out.println("first while loop:");
		countDown = 3;
		while(countDown > 0) {
			System.out.println("hello");
			countDown = countDown -1;
			
		}
		
		System.out.println("second while loop:");
		countDown = 0;
		while(countDown > 0) {
			System.out.println("hello");
			countDown = countDown -1;
			
		}
		
		System.out.println("first do-while loop:");
		countDown = 3;
		do
		{
			System.out.println("hello");
			countDown = countDown -1;
			
		}while(countDown>0);
		
		System.out.println("second do-while loo:");
		countDown = 0;
		do
		{
			System.out.println("hello");
			countDown = countDown - 1;
			
		}while(countDown > 0);
		

	}

}

출력결과

Flow of Control (제어 흐름)

branching 과 looping 두가지를 참고할 수 있다.

branching 과 looping은 boolean expressions 로 control 된다.

Branching mechanism :

-if , else if, else

-switch

Compound Statements

→ 명령어를 여러 줄 쓰는 경우 braces({ }) 기호 사용

else는 생략 가능

The Conditional Operator

if (n1 > n2) max = n1;
else         max = n2;

max = (n1 > n2) ? n1 : n2;   (conditional operator)

Boolean Expressions

  • and - && , or - || , not - !

-&, | 로도 사용 가능

*Short-Circuit

:&&의 경우 처음이 false이면 반드시 false이므로 이후 계산 수행x, ||의 경우 처음이 true이면 반드시 true이므로 이후 계산 수행x

→ 프로그램 실행 시간을 줄여줌(효율적) , 런타임 에러를 줄여준다.

ex1)

→ if, else if, else 를 사용하여 입력받은 값에 따른 tax 값을 계산해서 출력하는 프로그램

ex2)

→ switch 문을 사용하여 각각의 경우에 따른 출력값을 출력

-case2,3 처럼 비어 있는 경우 다음으로 넘어가서 case 4의 내용을 출력

-default는 해당 값이 없는 경우에 대해 출력

Using == with Strings

equality comparison을 위해 (==) 연산자를 사용한다.

이때, primitive type에서는 두 값을 비교하게 된다.

하지만 String class의 경우(==)연산자는 값을 비교하는 것이 아니라 같은 메모리 location을 가리키는 것인지 확인하는 용도로 사용된다.

따라서, String class의 값을 비교하기 위해서는 equals, eqaulsIgnoreCase와 같은 method를 사용하여 확인해야 한다.

Loops

-while, do-while, for statements 가 있다.

-loop에서 반복되는 부분의 코드를 body라고 한다.

-body 중에서 반복하는 부분을 iteration이라고 한다.

*while과 do-while의 차이

→while은 조건을 먼저 확인 후 body를 실행한다. 하지만, do-while의 경우 body를 먼저 실행한 뒤 조건을 evaluation한다. 따라서 do-while의 경우 반드시 1번은 body문이 실행된다.

ex3)

package chapter3;

public class chapter3_3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int countDown;
		
		System.out.println("first while loop:");
		countDown = 3;
		while(countDown > 0) {
			System.out.println("hello");
			countDown = countDown -1;
			
		}
		
		System.out.println("second while loop:");
		countDown = 0;
		while(countDown > 0) {
			System.out.println("hello");
			countDown = countDown -1;
			
		}
		
		System.out.println("first do-while loop:");
		countDown = 3;
		do
		{
			System.out.println("hello");
			countDown = countDown -1;
			
		}while(countDown>0);
		
		System.out.println("second do-while loo:");
		countDown = 0;
		do
		{
			System.out.println("hello");
			countDown = countDown - 1;
			
		}while(countDown > 0);
		

	}

}

출력결과

Flow of Control (제어 흐름)

branching 과 looping 두가지를 참고할 수 있다.

branching 과 looping은 boolean expressions 로 control 된다.

Branching mechanism :

-if , else if, else

-switch

Compound Statements

→ 명령어를 여러 줄 쓰는 경우 braces({ }) 기호 사용

else는 생략 가능

The Conditional Operator

if (n1 > n2) max = n1;
else         max = n2;

max = (n1 > n2) ? n1 : n2;   (conditional operator)

Boolean Expressions

  • and - && , or - || , not - !

-&, | 로도 사용 가능

*Short-Circuit

:&&의 경우 처음이 false이면 반드시 false이므로 이후 계산 수행x, ||의 경우 처음이 true이면 반드시 true이므로 이후 계산 수행x

→ 프로그램 실행 시간을 줄여줌(효율적) , 런타임 에러를 줄여준다.

ex1)

→ if, else if, else 를 사용하여 입력받은 값에 따른 tax 값을 계산해서 출력하는 프로그램

ex2)

→ switch 문을 사용하여 각각의 경우에 따른 출력값을 출력

-case2,3 처럼 비어 있는 경우 다음으로 넘어가서 case 4의 내용을 출력

-default는 해당 값이 없는 경우에 대해 출력

Using == with Strings

equality comparison을 위해 (==) 연산자를 사용한다.

이때, primitive type에서는 두 값을 비교하게 된다.

하지만 String class의 경우(==)연산자는 값을 비교하는 것이 아니라 같은 메모리 location을 가리키는 것인지 확인하는 용도로 사용된다.

따라서, String class의 값을 비교하기 위해서는 equals, eqaulsIgnoreCase와 같은 method를 사용하여 확인해야 한다.

Loops

-while, do-while, for statements 가 있다.

-loop에서 반복되는 부분의 코드를 body라고 한다.

-body 중에서 반복하는 부분을 iteration이라고 한다.

*while과 do-while의 차이

→while은 조건을 먼저 확인 후 body를 실행한다. 하지만, do-while의 경우 body를 먼저 실행한 뒤 조건을 evaluation한다. 따라서 do-while의 경우 반드시 1번은 body문이 실행된다.

ex3)

package chapter3;

public class chapter3_3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int countDown;
		
		System.out.println("first while loop:");
		countDown = 3;
		while(countDown > 0) {
			System.out.println("hello");
			countDown = countDown -1;
			
		}
		
		System.out.println("second while loop:");
		countDown = 0;
		while(countDown > 0) {
			System.out.println("hello");
			countDown = countDown -1;
			
		}
		
		System.out.println("first do-while loop:");
		countDown = 3;
		do
		{
			System.out.println("hello");
			countDown = countDown -1;
			
		}while(countDown>0);
		
		System.out.println("second do-while loo:");
		countDown = 0;
		do
		{
			System.out.println("hello");
			countDown = countDown - 1;
			
		}while(countDown > 0);
		

	}

}

출력결과

'Development > OOP(Java)' 카테고리의 다른 글

Ch6. Defining Classes(3)  (0) 2023.04.10
Project1 (Timetable application)  (0) 2023.04.05
Ch5. Defining Classes(2)  (0) 2023.04.03
Ch2. Console Input and Output  (0) 2023.04.01
Ch4. Defining Classes  (0) 2023.03.27

Static Methods

: object 없이 호출하여 사용가능한 method

- static method는 class에 속하며 class definition 내부에서 정의된다.

- static method를 정희할 때 static 이라는 keyoword를 사용한다.

   -> pulbic static returnedType myMethod (parameters)

        {...}

- static method는 호출 객체 대신 class 이름을 사용하여 호출한다.

   ex) returnedValue = Myclass.myMethod(arguments);

 

Pitfall : Invoking a Nonstatic Method Withn a Static Method

: 정적 메서드 내에서 비정적 메서드 호출

- 정적 메서드는 클래스의 instance variable을 참조할 수 없으며 클래스의 정적 메서드를 호출할 수 없다.

- 정적 메서드에는 this 값이 존재하지 않기 때문에 호출 객체에 대한 암시적,명시적 instance variable 혹은 메서드 사용이 불가하다.

- 다른 정적 메서드를 호출하는 것은 가능하다.

같은 Class 내부이므로 class name 생략하고 사용 가능
객체를 생성하고 method를 사용하는 경우

Static Variables

- static variables는 하나의 객체만이 아니라 클래스 전체에 속하는 변수이다.

   -> 각 객체가 하나의 복사본을 갖는 instance variable과 달리 클래스당 정적 변수의 복사본은 하나이다.

- 클래스의 모든 객체가 static variables를 읽고 쓸 수 있다.

- static methods는 instance variable에는 접근 불가하지만 static variables에는 접근가능하다.

- static variables는 instance variable처럼 선언되며 static 을 사용하여 선언한다.

   ex) private static int myStaticVariable;

- 정적 변수는 선언과 초기화를 동시에 수행 가능하다. 

   ex) private static int myStaticVariable = 0;

- 명시적으로 초기화되지 않은 경우 자동으로 초기화된다. (초기화 해주는 것이 이상적)

   -> boolean type : false, primitive types : 0, class type : null

- 정적 변수는 상수가 아닌 경우 항상 private으로 정의되어야 한다.

    -> 정적으로 정의된 상수의 경우 변경불가하므로 public으로 사용 가능하다.

    -> 해당 값이 변경불가함을 표현하기 위해 final 수식어를 사용해야 한다.

          ex) public static final int BIRTH_YEAR = 1954;

- 클래스 외부에서 상수를 참조하는 경우 클래스명을 사용하여 호출한다.

    ex) int year = MyClass.BIRTH_YEAR;

 

The Math class

: Math 클래스는 많은 수학적 methods를 제공

- java.lang 패키지에 포함되어있어 자동으로 import 되어 사용 가능하다. 

- 모든 methods와 data는 static으로 Math 클래스명과 함께 호출된다.

- Math 클래스는 E, PI 두가지 정의된 상수를 갖는다.

 

Math 클래스의 Methods

1. public static double pow (double base, double exponent)

-> 제곱을 연산

ex) Math.pow (2.0, 3.0) => 8.0

 

2. public static double abs(double argument)

public static float abs(float argument)

public static long abs(long argument)

public static int abs(int argument)

-> 해당 type 의 값의 절댓값을 return

ex) Math.abs(-6) => 6

 

3. public static double min(double n1, double n2)

public static float min(float n1, double n2)

public static long min(long n1, double n2)

public static int min(int n1, double n2)

-> 인자로 받은 값 중 최소값을 return

ex) Math.min(3, 2) => 2

 

4.  public static double max(double n1, double n2)

public static float max(float n1, double n2)

public static long max(long n1, double n2)

public static int max(int n1, double n2)

-> 인자로 받은 값 중 최댓값을 return

ex) Math.max(3, 2) => 3

 

5. public static long round(double argument)

public statci int round(float argument)

-> 인자로 받은 값을 반올림 연산하여 return

ex) Math.round(3.2) => 3 , Math.round(3.6) => 4

 

6. public statci double ceil(double argument)

-> 인자로 받은 값을 올림 연산하여 return

ex) Math.ceil(3.2) => 4.0, Math.ceil(3.6) => 4.0

 

7. public static double floor(double argument)

-> 인자로 받은 값을 내림 연산하여 return

ex) Math.floor(3.2) => 3.0 , Math.floor(3.9) => 3.0

 

8. public static double sqrt(double argument)

-> 인자로 받은 값의 제곱근을 연산하여 return

ex) Math.sqrt(4) => 2.0

 

Random Numbers

: Math 클래스는 난수를 생성하는 기능을 제공한다.

  public static double random()

  *Random 클래스는 flexible 한 난수값을 생성한다.

ex) double num = Math.random();

 

Wrapper class

: 기본 데이터 타입을 객체로 감싸는 클래스

primitive types : byte, short, int, long, float, double, char -> Byte, Short, Integer, Long, Float, Double, Character

- Wrapper class는 정의된 상수나 static methods를 포함한다.

 

Wrapper class 사용 이유

  1. 객체 형태로 데이터를 다룰 있다.
  2. 객체로 감싸지 않으면 기본 데이터 타입은 null 값을 가질 없다. 하지만 객체로 감싸면 null 값을 가질 있다.
  3. 객체로 감싸면 다양한 메소드를 사용할 있다.

Boxing

: 기본 데이터 타입을 Wrapper class의 객체로 변환하는 것

- 새로운 객체에는 원시 값의 복사본을 저장하는 instance variable을 포함

- 다른 클래스와 다르게 wrapper class는 인자 없는 생성자를 갖지 않는다.

ex) Integer integerObject = new Integer(42);

 

Unboxing

: Wrapper class의 객체를 기본 데이터 타입으로 변환하는 것

ex) int i = integerObject.intValue( );.  ->   인자를 갖지 않음

 

Automatic Boxing and Unboxing

- java 5.0 이후로는 자동으로 boxing , unboxing이 가능하다.

- 이전 설명처럼 new를 사용하여 객체를 생성하는 것이 아니라 자동으로 생성한다.

   ex) Integer integerObejct = 42;

-  wrapper 클래스 객체에서 원시 데이터 유형으로 변환하는 경우

   ex) int i  = integerObject;

 

Constants and Static Methods in Wrapper Classes

-Wrapper 클래스는 최댓값,최솟값을 제공하는 상수를 제공한다.

  ex) Integer.MAX_VALUE, Integer.MIN_VALUE, Double.MAX_VALUE, Double.MIN_VALUE

- Boolean 클래스는 두 상수에 대한 이름이 존재

  ex) Boolean.TRUE, Boolean.FALSE

- Wrapper 클래스는 문자열 표현의 숫자를 변환하는 정적 메서드를 포함한다.

   ex) Integer.parseInt, Long.parseLong

- Wrapper 클래스는 숫자값을 문자열 표현으로 변환하는 정적 메서드를 포함한다.

   ex) Double.toString(123.99); -> return "123.99"

- Character class에는 문자열 처리에 유용한 정적 메서드가 포함되어있다.

 

Character Class의 Methods

1. toUpperCase()

public static char toUpperCase(char argument)

-> 대문자로 변환, 문자가 아닌 경우 변화없음

ex) Character.toUpperCase('a') => return 'A'

 

2. toLowerCase()

public static char toLowerCase(char argument)

-> 소문자로 변환, 문자가 아닌 경우 변화없음

ex) Character.toLowerCase('A') => return 'a'

 

3. isUpperCase()

public static boolean isUpperCase(char argument)

-> 대문자인 경우 true 반환, 아닌 경우 false

ex) Character.isUpperCase('A') = > return true

 

4. isLowerCase()

public static boolean isLowerCase(char argument)

-> 소문자인 경우 true 반환, 아닌 경우 false

ex) Character.isLowerCase('a') => return false

 

5. isWhitespace()

publci static boolean isWhitespace(char argument)

-> 공백인 경우 true 반환 (빈칸, \t, \n  세 가지 경우에 해당)

ex) Character.isWhitespace(' ') => return true

 

6. isLetter()

public static boolean isLetter(char argument)

-> 인자가 문자인 경우 true 반환

ex) Character.isLetter('A') => return true, Character.isLetter('5') => return false

 

7. isDigit()

public static boolean isDigit(char argument)

-> 인자가 정수인 경우 true 반환

ex) Character.isDigit('5') => return true

 

8. isLetterOrDigit()

public static boolean isLetterOrDigit(char argument)

-> 인자가 문자거나 정수인 경우 true 반환

ex) Character.isLetterOrDigit('A') => true, Character.isLetterOrDigit('5') => true

 

Variables and memory

대부분의 데이터 유형의 값을 1byte 이상의 저장공간을 필요로한다.

- 여러개의 인접 바이트가 데이터를 유지하는데 사용됨

- 데이터를 저장하는 전체 덩어리를 memory location 이라고 한다.

- memory location의 첫번째 주소를 데이터의 주소로 사용한다.

 

main memory는 다양한 크기의 memory location의 list로 생각 할 수 있다.

 

Reference

- 모든 변수는 memory location에서 실행된다.

- 변수가 primitive type인 경우 변수의 값은 할당된 memory location에 저장된다. -> primitive type은 일정 양의 메모리를 필요로 함 

- 변수가 class type 인 경우, 객체가 위치한 메모리 주소만 할당된 memory location에 저장

   => primitive type 과 달리 클래스 변수 값은 memory address 혹은 reference 이다.

- 두 참조 변수는 같은 객체를 가리킬 수 있다.

   variable2 = variable1; => 같은 객체를 가리킨다.  

 

variable1, variable2 가 같은 객체에 대한 주소를 갖고 있다.

 

같은 객체를 참조하므로 객체가 변하면 variable1,variable2 모두 같은 값을 가리킨다.

 

 

 

 

 

 

'Development > OOP(Java)' 카테고리의 다른 글

Ch6. Defining Classes(3)  (0) 2023.04.10
Project1 (Timetable application)  (0) 2023.04.05
Ch3. Flow of Control  (0) 2023.04.04
Ch2. Console Input and Output  (0) 2023.04.01
Ch4. Defining Classes  (0) 2023.03.27

System.out.println

System.out →Console 출력 객체 (object)

println → console output 매서드(method)

print vs println

-print 매서드는 println과 다르게 줄바꿈을 포함하지 않음(개행문자 포함x)

→ println 의 다음 output은 새로운 줄에 출력, print의 경우 해당 줄에 그대로 이어서 출력

Printf

java에서의 printfsms C언어에서의 printf와 매우 유사하다.

System.out.printf는 여러 인자(argument)를 가질 수 있다.

첫번째 인수는 항상 format string이다.

첫 번째를 제외한 모든 인수는 화면에 출력되는 값

ex)

%6.2f → 6자리로 맞춤 (앞에서 부터 공백으로 채움) , 소수점 2번째자리까지 출력

%-8.2fEnd → “-”부호를 사용하여 왼쪽 정렬로 8자리수를 채우고(빈칸으로 채움) 소수점 2번째 자리까지 출력

Importing Packages and Classes

-JAVA의 라이브러리를 packages라고 한다.

-package는 class들의 모음으로 프로그램 접근이 용이하도록 한다.

-해당 package의 class를 사용하기 위해 import 문을 작성해야 한다.

 

ex)

import java.text.NumberFormat; → NumberFormat 클래스만 import

import java.text.*; → java.text 패키지에 있는 모든 클래스 import

*java.lang 패키지의 class는 자동적으로 모든 Java 프로그램에 import 된다.

Scanner Class

-keyboard의 입력을 받기 위해 Scanner Class를 포함한다.(Java 5.0 이상)

Scanner 클래스 사용을 위한 import → import java.util.Scanner (java.util 패키지에서 Scanner 클래스를 찾아 import)

ex)

Scanner keyboard = new Scanner(System.in);

->keyboar라는 이름의 Scanner 클래스 객체를 생성, system.in은 키보드 입력을 처리하는 객체

->Scanner 객체가 생성된 후 객체를 사용하여 키보드 입력을 수행

 

nextInt(), nextDouble()

-nextInt 매서드는 하나의 int값을 변수에 할당

-nextDouble 매서드는 하나의 double형 값을 변수에 할당

-다수의 입력은 whitespac(공백)으로 구분되어야 하며 적절한 매서드의 호출로 읽혀야 함

 

next()

-next()매서드는 공백이 아닌 하나의 string형을 읽음

ex)

String word1 = keyboard.next();

String word2 = keyboard.next();

input = jelly beans

=> word1 = jelly, word2 = beans

 

nextLine()

-nextLine 매서드는 keyboard 입력 전체를 읽음

nextLine이 텍스트를 읽을 때 엔터 입력시 ‘\n’를 읽으므로 다음 입력은 다음줄 부터 입력하게 된다.(‘\n’을 string 값으로 간주하지는 않음)

ex) String line = keyboard.nextLine(); → 문장 전체를 line 변수에 입력

 

useDelimiter(New Delimiter)

-키보드 입력의 구분 기호를 기준으로 문자열 입력

ex) String line = keyboard.useDelimiter(",") -> ,(쉼표) 를 기준으로 문자열 입력

 

 

 

'Development > OOP(Java)' 카테고리의 다른 글

Ch6. Defining Classes(3)  (0) 2023.04.10
Project1 (Timetable application)  (0) 2023.04.05
Ch3. Flow of Control  (0) 2023.04.04
Ch5. Defining Classes(2)  (0) 2023.04.03
Ch4. Defining Classes  (0) 2023.03.27

Introduction & class definition

class는 object-oriented programming(객체지향프로그래밍)의 가장 중요한 특성이다.

Java programming은 class로 구성되어있다.

-모든 program은 class

-모든 helping software 는 class로 구성

-사용자가 정의한 type도 모두 class

 

Class Definition

ex)기존에 사용하던 String, Scanner 모두 class이다.

 

A Class Is a Type(중요)

class type의 값을 object 혹은 class의 instance라고 한다.

A라는 class가 있을 때, 

-bla is of type A

-bla is an object of the class A

-bla is an instance of the class

라고 표현 가능하다.

class는 객체 혹은 메서드가 포함할 수 있는 data type을 결정한다.

 

The Contents of a Class Definition

class의 정의는 data items와 methods 를 구체화한다.

-Data items : fields, instance variables 라고 한다.

-Methods : 객체가 행할 수 있는 action

data items, methods는 객체의 member라고 한다.

 

The new Operator

class의 객체는 class type의 변수로 선언된다

-> ClassName classVar;

new operator는 객체를 생성하고 변수명과 연관지어 주기 위해 반드시 사용된다.

-> classVar = new ClassName();

합쳐서 간편하게 사용

-> ClassName classVar = new ClassName();

 

Instance Variable and Methods

Instance Variable은 다음과 같이 정의된다.

public String instanceVar1;

public int instanceVar2;

instancevariable 참조를 위해 다음과 같이 사용한다.

objectName.instanceVar1

objectName.instanceVae2

 

Method 정의는 heading ,body 두 부분으로 구분된다.

 

method는 실행 객체와 메서드 명을 사용하면 호출할 수 있다.

ex) classVar.myMethod();

 

More About Methods

methods에는 두 가지 종류가 있다.

-계산을 수행하고 값을 반환하는 methods ->heading 부분에 값의 type을 명시해줘야 한다. 

-action을 수행하는 methods( return value가 없고 void method라고 한다.) -> heading 부분에 void 사용

 

main은 void Method

main은 void methods로 값을 반환하지 않는다.

heading 부분을 다음과 같이 작성

 

local variables,blocks,parameters

Local Variables

method와 함께 선언된 변수를 local variable이라고 한다.

-> main 함수 변수는 모두 local 변수

-> 모든 method의 parameters는 local 변수

두 개의 methods가 각각의 같은 이름의 local 변수를 가져도 두개는 다른 변수라고 본다.

 

Global Variables

Java는 global 변수를 사용하지 않는다. (C, C++ 에서 사용)

 

Blocks

braces ( { } ) 로 구분된 compound statement를 block이라고 한다.

block 내에 선언된 local 변수는 해당 block에서 local이다. 하지만 해당 block 밖에서는 사용 할 수 없다.

 

Parameters of a Primitive Type

인자의 개수와 순서는 parameter list와 일치해야 한다.

각 인자의 type은 대응하는 parameter 와 호환 가능해야한다. (int, double은 서로 호환이 가능)

ex)

this Parameter

모든 instance variables 앞에는 <the calling object>. 을 사용한다.

calling object의 정확한 이름 대신 this를 사용할 수 있다.

ex) myInstanceVariable -> this.myInstanceVariable

<the calling object>는 기존에 생략되어있음, 대신에 this. 사용 가능

this 는 parameter, local variables 가 method에서 같은 이름으로 사용될 때 반드시 사용해야한다.

this 사용을 하지 않으면 instance가 local 로 해석된다.

The methods equals and toString

equals 는 두 객체의 내용을 비교하기 위한 method이며 boolean type이다. (내용 비교를 위해 "==" 사용  x)

toString은 객체의 data의 String 값을 반환하는 method이다.

 

Information Hiding & Encapsulation

Information Hiding

객체의 내부 상태나 구현 세부사항을 외부에서 접근하지 못하도록 숨기는 것을 의미

 

Encapsulation

Information Hiding 구현하는 방법 하나로 클래스 내부의 필드와 메소드를 캡슐화하여, 외부에서 직접적인 접근을 제한하고 클래스 내부의 메소드를 통해 필드의 값을 조작하도록 한다.

Java에서 Encapsulation 구현하기 위해, 필드를 private으로 선언하고, public으로 선언된 메소드(getter, setter) 통해 외부에서 필드에 접근할 있도록 하는 방식을 사용

 

-> 객체를 안정적으로 유지하기 위함!

API and ADT

API(Application Programming Interface)

프로그래밍에서 사용되는 인터페이스를 의미

즉, 프로그래머가 다른 프로그램, 라이브러리 또는 운영 체제와 상호 작용하기 위해 사용하는 일련의 규칙, 규약, 명령어 등을 제공

일반적으로, API는 소프트웨어의 기능을 사용할 수 있는 방법을 제공하며, 개발자가 필요한 기능을 호출하여 사용할 수 있음

 

ADT(Abstract Data Type)

데이터를 추상화한 개념입니다.

ADT 데이터와 해당 데이터를 다루는 연산을 정의한 추상적인 개념으로, 구체적인 구현 방법에 대한 정보를 숨김.

ADT 일반적으로 클래스나 인터페이스로 구현되며, 구현 방법은 사용자에게 숨겨져 있으므로, 인터페이스를 통해 추상화된 개념만 사용할 있음

 

public and private Modifiers

public -> instance 변수나 methods가 어디에서나 사용 될 수 있음

private -> instance 변수나 methods 가 class 외부에서 사용될 수 없음

모든 instance 변수를 private 으로 정의하는 것이 좋음

대부분의 methods는 public으로 정의되며 객체에게 접근 권한이 부여됨

class 내부에서 다른 methods 를 돕기 위한 method에 private으로 정의함

private으로 정의되어 있어 compile error 발생!

 

Accessor and Mutator Methods

Accessor Methods 는 개발자에게 객체의 instance variable 값을 얻을 수 있게 해줌

- data는 접근 가능하나 수정은 불가하다.

-accessor methods는 주로 get이라는 단어로 시작함

 

Mutator methods는 개발자에게 객체의 instance variable 값을 수정할 수 있께 해줌

-incoming data는 tested/filtered 된 data

-mutator methods 는 주로 set 이라는 단어로 시작

 

A Class Has Access to Private Members of All Objects of the Class

인자에 class type을 선언하는 경우에 private member에 접근이 가능하다.

DataSecondTry을 인자에 선언하였기 때문에 private member에 접근이 가능

 

Oveloading

2개이상의 methods가 같은 class에서 같은 method 이름을 갖는 경우이다.

ex)

overloading 예시

overloading이 가능하려면 다른 signatures를 가져야 한다. (인자의 개수 or 인자의 type이 달라야 함)

 

Overloading and Automatic Type Conversion

overloading이 일어나 signature를 찾지 못하는 경우 automastic type conversion이 일어나 프로그램이 정상 작동하지 않을수도 있음overloading 에서 return type은 signature 가 아니므로 사용할 수 없다.

 

Constructors(생성자)

constructor는 instance 변수를 초기화 하기 위한 특별한 method 이다.

public ClassName(anyParameters){code}

-생성자는 class명과 동일한 이름을 사용

-생성자는 return type이 없으며 void 도 아니다.

-생성자는 overloaded 된다.

 

생성자는 new 를 사용하여 새로운 class 객체를 생성할 때 호출된다.

생성자에 의해 처음 action은 instance 변수로 객체를 생성하는 것이다.

생성자의 정의에 따라 다른 method를 이후에 불러일으키는 것이 가능하다.

 

Include a No -Argument Constructor

class에 생성자를 포함하지 않으면 자동적으로 default, no-argument constructor를 생성한다.

이것은 인자를 갖지 않고 초기화 진행을 하지 않지만 객체만 생성하는 것이다.

 

Default Variable Initializations

Instance 변수는 자동적으로 초기화 된다.

-boolean type은 false로 초기화

-primitive types는 0으로 초기화

-class type은 nul값으로 초기화

*local 변수는 자동으로 초기화 되지 않는다.

 

예시를 통한 확인

that.i의 경우 caller object 의 값을 가져옴

 

 

 

 

'Development > OOP(Java)' 카테고리의 다른 글

Ch6. Defining Classes(3)  (0) 2023.04.10
Project1 (Timetable application)  (0) 2023.04.05
Ch3. Flow of Control  (0) 2023.04.04
Ch5. Defining Classes(2)  (0) 2023.04.03
Ch2. Console Input and Output  (0) 2023.04.01

+ Recent posts