(101)

Object

Object - java.lang 패키지 중 가장 많이 사용되는 클래스(모든 자바 클래스들의 최고 조상 클래스) - 필드를 가지지 않으며 11개의 메서드로 구성 메서드 설명 protected Object clone() 해당 객체의 복사본을 생성 boolean equals(Object obj) 두 객체가 같은지 protected void finalize() 가비지 컬렉터가 객체의 리소스를 정리하기 위해 호출 ClassgetClass() 클래스 타입 반환 int hashCode() 해시 코드 반환 void notify() 대기하고 있는 하나의 스레드를 다시 실행할 때 void notifyAll() 대기하고 있는 하나의 모든 스레드를 다시 실행할 때 String toString() 객체의 정보를 문자열로 반환..

날짜와 시간 / Date, Time, Calender

- Date는 JDK 1.0부터, Calender는 JDK 1.1부터 제공되었다. - JDK 1.8부터 java.time 패키지로 Calender와 Date의 단점을 개선한 클래스들이 추가되었다. - Date, Calender의 사용을 지양하자 Date // 객체를 생성하여 현재 날짜 출력해보기 Date myDate = new Date(); System.out.println(myDate); // getTime : 1970년 1월 1일 00:00:00 UTC부터 주어진 날짜 사이의 경과 시간을 밀리초로 나타냄 System.out.println(myDate.getTime()); // 1670634141973 myDate.setTime(1639426833210L); System.out.println(myDat..

Wrapper

Wrapper - 기본 타입의 데이터를 객체로 취급해야 하는 경우 사용한다 - 래퍼클래스는 인스턴스에 저장된 값을 변경할 수 없다 ※ Integer / Character 클래스는 기본 타입과 이름이 다르다 기본타입 래퍼 클래스 byte Byte short Short int Integer long Long flot Float double Double char Character boolean Boolean Boxing & Unboxing - Boxing : 기본 타입의 데이터를 래퍼 클래스의 인스턴스로 변환하는 과정 - Unboxing :반대로 인스턴스에 저장된 값을 기본 타입의 데이터로 꺼내는 과정 Integer num = new Integer(1); // 박싱 int n = num.intValue(); ..

Enum

Enum - Enum을 사용하여 열거체를 정의할 수 있다 ㅡ> 상수들의 집합 - 상수의 의미를 확실하게 전달 + 프로그램의 안정성 향상 - 선언된 순서에 따라 index값을 가진다 - 상수들은 모두 대문자로 선언해야 한다 - 메서드 사용가능 public static final String MON = "Monday"; public static final String TUE = "Tuesday"; public static final String WED = "Wednesday"; // Enum을 이용하면 특정 상수값을 사용하기 위해 일일이 선언하지 않아도 된다. public enum Day { MON, TUE, WED, THU, FRI, SAT, SUN } // 생성자와 final필드를 추가할 수 있다 // ..

예외처리 Exception

예외처리(Exception) - 오류가 났을 때 try catch, throw를 이용하여 오류를 처리하는 것 - 오류가 발생하면 프로그램이 비정상적으로 종료되지만, 예외처리 추가 시 정상적인 실행상태로 되돌릴 수 있다 - 예외처리를 통해 사용자 입장에서 생각하여 사용자가 할 법한 실수들을 대비 - Exception : 프로그램 실행도중 종료될 수 있는 문제와 연관되어 예외처리를 선택적으로 하거나 꼭 해야하는 클래스들의 최상위 클래스 - Error 클래스 : 프로그램 실행 도중 해결할 수 있는 문제가 아니라 이후 발견되어 처리해야하는 문제들이 연관되어 있는 클래스 예외가 발생하는 순간들 System.out.println(10/0); // ArithmeticException int[] arr = {1,2,3..

인터페이스 (Interface)

인터페이스 모든 기능을 추상화로 정의만 하고 구현은 하지 않은 것 클래스와 인터페이스는 서로 상속받을 수 없다. 인터페이스끼리 상속가능 클래스는 다중 상속이 불가능하지만 인터페이스는 다중 구현이 가능하다 일반 메서드를 사용할 수 없다 필드는 상수 값만 가질 수 있다 implements 키워드를 사용하여 인터페이스를 '상속'이 아닌 '구현'한다. interface A {// 인터페이스 abstract void test1();// 추상 메서드 abstract void test2(); } interface B { void test3(); // 인터페이스에서 abstract 키워드를 생략할 수 있다. void test4(); } class C implements A , B { // 인터페이스는 다중 구현이 가능..

추상화

추상화 공통된 특징을 묶어 하나의 클래스로 정의 (공통된 특징을 파악하는것이 중요) 상속으로 사용해야하지만 다중상속 불가능 객체 생성이 불가능 접근제어자, 리턴타입 사이에 abstract라는 키워드를 사용 자식 클래스들이 오버라이딩을 통해 메서드를 구현 abstract class Animal { // 추상 메서드 추상클래스 안에서 선언만 하고 {}대신 ;를 사용 abstract void howl(); } class Cat extends Animal { void howl() { System.out.println("야옹"); } } class Dog extends Animal { void howl() { System.out.println("멍멍"); } } public class Run { public st..

캡슐화와 접근제어자, getter&setter

캡슐화 연관된 목적을 가지는 변수, 함수를 하나의 클래스로 묶어 외부에서 쉽게 접근하지 못하도록 은닉하는 것 외부에서 내부 정보에 접근, 변경을 불가능하도록 처리하고 해당 객체가 제공하는 필드와 메서드를 통해 접근이 가능 객체 정보 손상과 오용을 방지하고 데이터가 변경되어도 다른 객체에 영향을 주지 않는다 캡슐화는 접근제어자를 통해 이루어진다 접근제어자 public : 접근의 제한이 없음 protected: 동일한 패키지 내에 존재하거나 상속받은 클래스에서 접근 가능 default : 동일한 패키지 내에서만 접근 가능 / 아무런 명시가 없다면 디폴트값 private : 해당 클래스 내에서만 접근 가능 Getter & Setter 객체를 외부에서 읽고 변경하게 되면 객체의 무결성(변하지 않는 형태)이 깨질..

Object

Tech/Java & Spring 2022. 12. 10. 12:03
728x90
728x90

Object


- java.lang 패키지 중 가장 많이 사용되는 클래스(모든 자바 클래스들의 최고 조상 클래스)

- 필드를 가지지 않으며 11개의 메서드로 구성

메서드 설명
protected Object clone() 해당 객체의 복사본을 생성
boolean equals(Object obj) 두 객체가 같은지
protected void finalize() 가비지 컬렉터가 객체의 리소스를 정리하기 위해 호출
Class<T>getClass() 클래스 타입 반환
int hashCode() 해시 코드 반환
void notify() 대기하고 있는 하나의 스레드를 다시 실행할 때
void notifyAll() 대기하고 있는 하나의 모든 스레드를 다시 실행할 때
String toString() 객체의 정보를 문자열로 반환
void wait() 스레드가 notify()나 notifyAll()를 실행할 때까지 현재 스레드를 일시적으로 대기시킬 때
void wait(long timeout) 스레드가 notify()나 notifyAll()를 실행하거나 전달받은 시간이 지날 때까지 일시적으로 대기시킬 때 호출함.
void wait(long timeout, int nanos) 스레드가 notify()나 notifyAll()를 실행하거나 전달받은 시간이 지나거나 다른 스레드가 현재 스레드를 인터럽트(interrupt) 할 때까지 일시적으로 대기시킬 때

Clone

- 데이터의 보호를 이유로 Cloneable 인터페이스를 구현한 클래스의 인스턴스가 사용 가능

- 필드값만을 복사하기 때문에 필드값이 배열이나 인스턴스면 제대로 복제할 수 없다

   → 해당 클래스에서 오버라이딩하여 재정의

class cloneExam implements Cloneable{
	
	@Override
	protected cloneExam clone(){
		Object ob = null;
		try {
			ob = super.clone();
		}catch(CloneNotSupportedException e) {			
		}
		return (cloneExam)ob;
	}
}

equals

- 해당 인스턴스를 매개변수로 전달받는 참조 변수와 비교

- 서로 다른 두 객체는 언제나 false

ExamMain car01 = new ExamMain();
ExamMain car02 = new ExamMain();		 

System.out.println(car01.equals(car02));

car01 = car02;
System.out.println(car01.equals(car02));

// Console
false
true

finalize

- 자바 9부터 사용불가능

- 배열이나 객체를 Garbage Collector를 사용해 힙 영역에서 제거

- 사용자가 해당 메서드를 직접 사용하려면 오버라이딩

Garbage Collection(GC)
- 메모리 관리법 중 하나
- 시스템에서 더이상 사용하지 않는 동적 할당된 메모리 블럭을 찾아 자동으로 다시 사용 가능한 자원으로 회수
Garbage Collector(JVM에 있음) : 가비지 컬렉션을 수행하는 부분

toString

- 인스턴스에 대한 정보를 문자열로 반환 → (클래스 이름/구분자 '@'/8자리 16진수)의 해시값

728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

배열 (Array)

Tech/Java & Spring 2022. 12. 10. 10:33
728x90
728x90

배열은 자료형의 집합이다

String[] week = {"월", "화", "수", "목", "금", "토", "일"};

// 배열의 길이는 고정되어 있다
String[] week = new String[7];
week[0] = "월";
week[1] = "화";
week[2] = "수";
week[3] = "목";
week[4] = "금";
week[5] = "토";
week[6] = "일";

// 배열의 길이를 설정하지 않았기 때문에 오류가 발생한다
String[] week = new String[];

// 간단한 배열 출력
for (int i=0; i<week.length; i++) {
    System.out.print(week[i]);         // Console : 월화수목금토일
}

// ArrayIndexOutOfBoundsException
System.out.println(weeks[7]);

 

관련 메서드


// binarySearch : 해당 배열에서 index위치의 값을 검색한 후 반환
int[] arr = new int[1000];
    for(int i = 0; i < arr.length; i++) {
        arr[i] = i;
    }	 
System.out.println(Arrays.binarySearch(arr, 333));    // Console : 333

// copyOf(arr, length) : 해당 배열의 length만큼 복사
// copyOf(arr, from, to) : 해당 배열의 from값의 index부터 to이전까지의 index의 값 복사
int[] arr1= {1,2,3,4,5};
int[] arr2= Arrays.copyOf(arr1, 3);
int[] arr3= Arrays.copyOfRange(arr1, 2, 5);
for(int i=0; i<arr2.length; i++) {
    System.out.print(arr2[i]+" ");             // Console : 1 2 3 
}
System.out.println(); // 개행
for(int i=0; i<arr3.length; i++) {
    System.out.print(arr3[i]+" ");            // Console : 3 4 5 
}

// fill : 배열의 모든 요소를 특정 값으로 초기화
int[] arr4 = new int[5];		
Arrays.fill(arr4, 7);
for(int i=0; i<arr4.length; i++) {
    System.out.print(arr4[i]);               // Console : 77777
}

// sort : 오름차순 정렬
int[] arr5 = {5,7,3,9,15,233};
Arrays.sort(arr5);
for(int i=0; i<arr5.length; i++) {
    System.out.print(arr5[i]+" ");           // Console : 3 5 7 9 15 233
}
728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

날짜와 시간 / Date, Time, Calender

Tech/Java & Spring 2022. 12. 10. 09:37
728x90
728x90

- Date는 JDK 1.0부터, Calender는 JDK 1.1부터 제공되었다.

- JDK 1.8부터 java.time 패키지로 Calender와 Date의 단점을 개선한 클래스들이 추가되었다.

- Date, Calender의 사용을 지양하자

 

Date


// 객체를 생성하여 현재 날짜 출력해보기
Date myDate = new Date();
System.out.println(myDate);

// getTime : 1970년 1월 1일 00:00:00 UTC부터 주어진 날짜 사이의 경과 시간을 밀리초로 나타냄
System.out.println(myDate.getTime());     // 1670634141973

myDate.setTime(1639426833210L);
System.out.println(myDate.getTime());       // 왜 안쓰는지 알거같다

// SimpleDateFormat으로 String타입 날짜를 date로 변환하여 사용.
String myString = "20221210";
SimpleDateFormat dtFormat = new SimpleDateFormat("yyyyMMdd");
Date mydate = dtFormat.parse(myString); // throws ParseException

System.out.println(mydate); // Sat Dec 10 00:00:00 KST 2022

 

위 예시만 봐도 너무 불편하다

 

Calender


- 추상클래스이기 때문에 객체를 직접 생성할 수 없다

 

Field(Static int) 설명
YEAR 현재 년도
MONTH 현재 월 (0~11의 값)
DATE / DAY_OF_MONTH 몇 일인지(날짜)
DAY_OF_YEAR 현재 년도의 날짜
DAY_OF_WEEK 현재 요일 ( 일요일 1 ~ 토요일 7)
WEEK_OF_YEAR 1년 중 몇 번째 주인지
WEEK_OF_MONTH 현재 월에서 몇 째 주인지
HOUR 12시간 단위의 시간 (0~11)
HOUR_OF_DAY 24시간 단위의 시간 (0~23)
MINUTE 분 (0~59)
SECOND 초 (0~59)
MILLISECOND 밀리 세컨드 단위

 

Calendar today = Calendar.getInstance();
System.out.println("올 해의 년도 : " + today.get(Calendar.YEAR));
System.out.println("월(0~11, 0:1월): " + today.get(Calendar.MONTH));
System.out.println("올 해의 몇 째 주: " + today.get(Calendar.WEEK_OF_YEAR));
System.out.println("이 달의 몇 째 주: " + today.get(Calendar.WEEK_OF_MONTH));
System.out.println("이 달의 몇 일: " + today.get(Calendar.DATE));
System.out.println("이 달의 몇 일: " + today.get(Calendar.DAY_OF_MONTH));
System.out.println("올 해의 몇 일: " + today.get(Calendar.DAY_OF_YEAR));
System.out.println("요일(1~7, 1:일요일): " + today.get(Calendar.DAY_OF_WEEK));
System.out.println("이 달의 몇 째 요일: " + today.get(Calendar.DAY_OF_WEEK_IN_MONTH));
System.out.println("시간(0~11): " + today.get(Calendar.HOUR));
System.out.println("시간(0~23): " + today.get(Calendar.HOUR_OF_DAY));
System.out.println("분(0~59): " + today.get(Calendar.MINUTE));
System.out.println("초(0~59): " + today.get(Calendar.SECOND));

// Console
올 해의 년도 : 2022
월(0~11, 0:1월): 11
올 해의 몇 째 주: 50
이 달의 몇 째 주: 2
이 달의 몇 일: 10
이 달의 몇 일: 10
올 해의 몇 일: 344
요일(1~7, 1:일요일): 7
이 달의 몇 째 요일: 2
시간(0~11): 9

 

JAVA.TIME


날짜 가져오기


LocalDate nowDate = LocalDate.now();
LocalDate ofDate = LocalDate.of(2022, 12, 10);
LocalDateTime nowDateTime = LocalDateTime.now();
LocalDateTime ofDateTime = LocalDateTime.of(2022, 12, 10, 9, 40, 13);

System.out.println(nowDate);           // 현재 년/월/일
System.out.println(ofDate);	       // ofDate 리턴
System.out.println(nowDateTime);      // 현재 년/월/일/시/분/초/밀리초
System.out.println(ofDateTime);       // ofDateTime 리턴

활용하기


// 내일의 날짜
LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime tomorrow = localDateTime.plusDays(1);
System.out.println(tomorrow);

// 내일 날짜의 끝 시간(23:59:59.99999...)
LocalDateTime localDateTime = LocalDateTime.now().plusDays(1).with(LocalTime.MAX);
System.out.println(localDateTime);

// 정오
LocalDateTime localDateTime = LocalDateTime.now().with(LocalTime.NOON);
System.out.println(localDateTime);

//자정
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String date = LocalDate.now().atStartOfDay().format(dateTimeFormatter);		
System.out.println(date);

// LocalDate(Time) → String
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		
LocalDate.now().format(DateTimeFormatter.ISO_DATE);


// String → LocalDate(Time)
LocalDateTime.parse("2018-12-11 13:43:21.221",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));   

LocalDate.parse("2018-12-11");

// 요일

// 현재 기준 가장 가까운 다음 토요일
LocalDateTime.now().with(TemporalAdjusters.next(DayOfWeek.SATURDAY));

// 입력한 월의 3번째 토요일
LocalDate.of(2022, 12, 10).with(TemporalAdjusters.dayOfWeekInMonth(3, DayOfWeek.SATURDAY));

// 입력한 월의 첫 번째 토요일
LocalDate.of(2022, 12, 10).with(TemporalAdjusters.firstInMonth(DayOfWeek.SATURDAY));

 

 

728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

Wrapper

Tech/Java & Spring 2022. 12. 10. 09:04
728x90
728x90

Wrapper


- 기본 타입의 데이터를 객체로 취급해야 하는 경우 사용한다

- 래퍼클래스는 인스턴스에 저장된 값을 변경할 수 없다

※ Integer / Character 클래스는 기본 타입과 이름이 다르다

 

기본타입 래퍼 클래스
byte Byte
short Short
int Integer
long Long
flot Float
double Double
char Character
boolean Boolean

 

Boxing & Unboxing


 - Boxing : 기본 타입의 데이터를 래퍼 클래스의 인스턴스로 변환하는 과정

 - Unboxing :반대로 인스턴스에 저장된 값을 기본 타입의 데이터로 꺼내는 과정

Integer num = new Integer(1); // 박싱
int n = num.intValue();        // 언박싱
System.out.println(n);


// 오토 박싱 / 언박싱
// JDK 1.5부터는 박싱과 언박싱이 필요한 상황에 컴파일러가 자동으로 처리해준다
Character ch = 'A'; // Character ch = new Character('A'); 오토박싱
char c = ch;        // char c = ch.charValue();           오토언박싱
System.out.println(c);

Console
1
A
// == 연산자를 사용하게 되면 주소값을 비교한다
// ㅡ> equals를 사용
Integer num1 = new Integer(1);
Integer num3 = new Integer(1);

System.out.println(num1==num3);
System.out.println(num1.equals(num3));

// Console
false
true
728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

Enum

Tech/Java & Spring 2022. 12. 10. 08:58
728x90
728x90

Enum


- Enum을 사용하여 열거체를 정의할 수 있다 ㅡ> 상수들의 집합

- 상수의 의미를 확실하게 전달 + 프로그램의 안정성 향상

- 선언된 순서에 따라 index값을 가진다

- 상수들은 모두 대문자로 선언해야 한다

- 메서드 사용가능

 

public static final String MON = "Monday";
public static final String TUE = "Tuesday";
public static final String WED = "Wednesday";

// Enum을 이용하면 특정 상수값을 사용하기 위해 일일이 선언하지 않아도 된다.
public enum Day {
	MON, TUE, WED, THU, FRI, SAT, SUN
}
// 생성자와 final필드를 추가할 수 있다
// 열거형 상수와 관련된 값을 생성자를 통해 연결시킬 경우 세미콜론을 붙인다
public enum Day {
	MON("monday"), TUE("tuesday"), WED("wednesday"),
    THU("thursday"), FRI("friday"), SAT("saturday"), SUN("sunday");
	
	private final String fullName;
	
	Day(String fullName){
		this.fullName=fullName;
	}
	
	public String getfullName() {
		return fullName;
	}	
}


System.out.println(Day.MON.name());
System.out.println(Day.TUE.getfullName());
// Console
MON
tuesday

 

Enum 메서드


https://limkydev.tistory.com/66 참조

Day[] va = Day.values();
System.out.println(va[6]);

int ord = Day.THU.ordinal();
System.out.println(ord);

Day day1 = Day.valueOf("MON");
System.out.println(day1);

// Console
SUN
3
MON
728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

예외처리 Exception

Tech/Java & Spring 2022. 12. 9. 21:19
728x90
728x90

예외처리(Exception)


- 오류가 났을 때 try catch, throw를 이용하여 오류를 처리하는 것

- 오류가 발생하면 프로그램이 비정상적으로 종료되지만, 예외처리 추가 시 정상적인 실행상태로 되돌릴 수 있다

- 예외처리를 통해 사용자 입장에서 생각하여 사용자가 할 법한 실수들을 대비

- Exception : 프로그램 실행도중 종료될 수 있는 문제와 연관되어 예외처리를 선택적으로 하거나 꼭 해야하는 클래스들의 최상위 클래스

- Error 클래스 : 프로그램 실행 도중 해결할 수 있는 문제가 아니라 이후 발견되어 처리해야하는 문제들이 연관되어 있는 클래스

 

예외가 발생하는 순간들


System.out.println(10/0);   // ArithmeticException
int[] arr = {1,2,3};
System.out.println(arr[3]);       // ArrayIndexOutOfBoundsException

 

try~catch를 이용한 예외처리


try{
	System.out.println(10/0);
} catch(Exception e){
	System.out.println("0으로 나누지마세요");
}

// Console
0으로 나누지마세요
try문 안에서 코드가 실행되다가 예외가 발생하는 행에서 즉시 catch안의 문장을 실행한다

try{
	int[] arr = {1,2,3};
	System.out.println(arr[3]);
   	System.out.println("배열 실행 완료");  // 실행되지 않는다
} catch(Exception e) {
	System.out.println("없는 배열 불러내지마세요");
}

// Console
없는 배열 불러내지마세요

예외가 발생해도 반드시 실행되어야 하는 부분이 있다면 finally를 이용한다

try{
	int[] arr = {1,2,3};
	System.out.println(arr[3]);
	System.out.println("배열 실행 완료");  // 실행되지 않는다
} catch(Exception e) {
	System.out.println("없는 배열 불러내지마세요");
} finally {
	System.out.println("배열 실행 완료");        // 예외처리가 되어도 무조건 실행
}

// Console
없는 배열 불러내지마세요
배열 실행 완료

 

예외 던지기 (throws)


- 강제로 예외를 발생시키고 싶을 때 사용

- Throwable : 모든 에러, 예외의 최상위 클래스

- 메서드를 호출한 곳에서 예외를 처리하라고 떠넘기는 것

- 호출한 곳에서는 반드시 예외처리 관련 코드가 필요하다

- 예외를 발생시키는 키워드는 throw이고 메서드에 선언하는 키워드는 throws이다

 

// throw를 이용하여 예외를 떠넘겼지만 코드 길이가 길어지고 가독성이 좋지 않음

public class Except {	
	public static void main(String[] args) {
		exam1();
    	exam2();
    	exam3();    
	}

    public static void exam1() {
        try {
            throw new ArrayIndexOutOfBoundsException("에러");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }
    }

    public static void exam2() {
        try {
            throw new ArithmeticException("에러");
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }

    public static void exam3() {
        try {
            throw new NullPointerException("에러");
        } catch (NullPointerException e) {
            System.out.println(e.getMessage());
        }
    }
}

// 자신을 호출한 메서드에게 예외를 전달하여 예외 처리를 떠맡긴다

public class Except {
	
	public static void main(String[] args) {
		try{
			exam1();
			exam2();
			exam3();
		}catch(ArrayIndexOutOfBoundsException | ArithmeticException | NullPointerException e) {
			System.out.println(e.getMessage());
		}
	}
	
	public static void exam1() throws ArrayIndexOutOfBoundsException{ 
		throw new ArrayIndexOutOfBoundsException("에러");
	}

	
	public static void exam2() throws ArithmeticException{
		throw new ArithmeticException("에러");
	}

			 
	public static void exam3() throws NullPointerException{
		throw new NullPointerException("에러");
	}
}


exam1에서 에러가 나게되면 아래의 exam2와 exam3 메서드는 호출되지 않는다
>> 어디에 사용하는지. 어디서 throw를 통해 넘기는지가 중요하다

// Console
에러

 

 

getMessage :에러의 원인만을 출력
toString : 에러의 Exception내용과 원인 출력
printStackTrace : 에러의 발생 근원지를 찾아 단계별로 에러 출력
728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

인터페이스 (Interface)

Tech/Java & Spring 2022. 12. 4. 15:50
728x90
728x90

인터페이스

  • 모든 기능을 추상화로 정의만 하고 구현은 하지 않은 것
  • 클래스와 인터페이스는 서로 상속받을 수 없다. 인터페이스끼리 상속가능
  • 클래스는 다중 상속이 불가능하지만 인터페이스는 다중 구현이 가능하다
  • 일반 메서드를 사용할 수 없다
  • 필드는 상수 값만 가질 수 있다
  • implements 키워드를 사용하여 인터페이스를 '상속'이 아닌 '구현'한다.
interface A {	// 인터페이스
	
	abstract void test1();	// 추상 메서드
	abstract void test2();	
}

interface B {
	
	void test3(); // 인터페이스에서 abstract 키워드를 생략할 수 있다.
	void test4();	
}

class C implements A , B { // 인터페이스는 다중 구현이 가능하다.

	@Override
	public void test1() {
		
	}

	@Override
	public void test2() {
		
	}

	@Override
	public void test3() {
		
	}

	@Override
	public void test4() {
		
	}
}

 

 

  • 인터페이스 타입으로 객체를 구현할 수 있다
interface Person {	
}

class Children implements Person{	
}

class Student  implements Person{	
}

class Adult    implements Person{	
}

public class Exapmle {

	public static void main(String[] args) {
		
		Person c = new Children();	// 인터페이스의 타입으로 객체 생성
		Person s = new Student();
		Person a = new Adult();		
	}	
}

추상클래스 vs 인터페이스

추상클래스

  1. 인스턴스 생성보다는 상속 목적으로 사용한다
  2. 추상 메서드 및 일반 메서드, 생성자, 필드도 포함할 수 있다
인터페이스

  1. 제공할 기능을 정의하는 데 사용한다
  2. 추상 메서드와 상수만 포함할 수 있다
728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

추상화

Tech/Java & Spring 2022. 12. 4. 15:36
728x90
728x90

추상화

  • 공통된 특징을 묶어 하나의 클래스로 정의 (공통된 특징을 파악하는것이 중요)
  • 상속으로 사용해야하지만 다중상속 불가능
  • 객체 생성이 불가능
  • 접근제어자, 리턴타입 사이에 abstract라는 키워드를 사용
  • 자식 클래스들이 오버라이딩을 통해 메서드를 구현
abstract class Animal {
	
    // 추상 메서드 추상클래스 안에서 선언만 하고 {}대신 ;를 사용
	abstract void howl();	              
}

class Cat extends Animal {

	void howl() {
		System.out.println("야옹");
	}
}

class Dog extends Animal {
	
	void howl() {
		System.out.println("멍멍");
	}
}

 

public class Run {

    public static void main(String[] args) {

        // Animal a = new Animal(); 추상 클래스는 인스턴스를 생성할 수 없음.

        Cat c = new Cat();
        Dog d = new Dog();

        c.howl();
        d.howl();
    }
}


// Console
// 야옹
// 멍멍
728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

캡슐화와 접근제어자, getter&setter

Tech/Java & Spring 2022. 12. 4. 14:42
728x90
728x90

캡슐화

  • 연관된 목적을 가지는 변수, 함수를 하나의 클래스로 묶어 외부에서 쉽게 접근하지 못하도록 은닉하는 것
  • 외부에서 내부 정보에 접근, 변경을 불가능하도록 처리하고 해당 객체가 제공하는 필드와 메서드를 통해 접근이 가능
  • 객체 정보 손상과 오용을 방지하고 데이터가 변경되어도 다른 객체에 영향을 주지 않는다
  • 캡슐화는 접근제어자를 통해 이루어진다

접근제어자

  • public : 접근의 제한이 없음
  • protected: 동일한 패키지 내에 존재하거나 상속받은 클래스에서 접근 가능
  • default : 동일한 패키지 내에서만 접근 가능 / 아무런 명시가 없다면 디폴트값
  • private : 해당 클래스 내에서만 접근 가능

Getter & Setter

  • 객체를 외부에서 읽고 변경하게 되면 객체의 무결성(변하지 않는 형태)이 깨질 수 있음
  • getter&setter 메서드를 통해 데이터를 받거나 변경
public class member {

// private로 선언해 놓았기 때문에 member클래스 내에서만 접근 가능
	private String id;
	private String pw;
	private int age;

//getter
	public String getId() {
		return id;
	}
	public String getPw() {
		return pw;
	}
	public int getAge() {
		return age;
	}

//setter
	public void setId(String id) {
		this.id = id;
	}
	public void setPw(String pw) {
		this.pw = pw;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

// 접근을 위해 getter & setter 활용
// 입력=set , 가져올 때=get을 사용

 

728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

방명록