Ch.3-3 상속과 다형성

상속 이유

재사용성 , 중복 제거, 계층적 분류 및 관리

특징

다중 상속 불가 (부모 여러명x)

메소드 오버라이딩

오버라이딩시 부모클래스 메소드 무시하고 자식 메소드 실행

상속했을 때 생성자 특징

  1. 지시가 없으면 자식 클래스에서도 부모 클래스의 기본 생성자 호출
  2. super()를 이용한 명시적 부모 클래스 생성자 호출(자식 생성자 코드 뒤에 호출 x)
    부모 클래스(Point) 생성자
public Point(int x, int y) {
		this.x = x;
		this.y = y;	
	}

자식 클래스(ColorPoint) 생성자

 	public ColorPoint(int x, int y, String color) {
		super(x,y);
		this.color = color;
        //super(x,y) : 오류
	}

객체의 형변환

업캐스팅

자식클래스가 부모클래스 타입으로 변환되는 것
명시적으로 타입 변환을 하지 않아도 된다.

다운 캐스팅

업캐스팅 된 것을 원래대로 되돌리는 것
명시적으로 변환해야함

public class StudentTest {
	public static void main(String[] args) {
	Student s1 = new Student();
		s1.setGrade(1);
		
		Person p1 = s1; 	//upcasting(암시적,Implicity)
		p1.setName("둘리");		
		
		Student s2 = (Student)p1;	//downcasting(명시적, explicity)
		s2.setMajor("cs");
        }
}

Ch.3-4 추상 클래스와 인터페이스

추상 클래스

실체 클래스의 공통적인 특성들을 추출해 선언한 클래스
객체 직접 생성해서 사용 불가
확장을 위한 용도
하나 이상의 추상 메소드를 가진다 (없으면 자식클래스에 선언해야함)
-> 추상 메소드가 없어도 추상 클래스일 수 있음

인터페이스

클래스들 사이의 유사한 특성(변수,메소드)을 부자연스러운 상속 관계를 설정하지 않고 얻어냄

특징

다중 상속 가능 (+ 인터페이스 간 다중 상속 가능)
인터페이스를 구현한 클래스에서 추상 메소드 반드시(인터페이스에 선언한 메소드) 정의해야 함

Ch.3-4-6 일반클래스 vs 추상 클래스 vs 인터페이스

ch.3-4-7 Instanceof 연산자

		System.out.println(circle instanceof Object); // circle이 Object클래스의 인스턴스인지
		System.out.println(circle instanceof Shape); //circle이 Shape클래스의 인스턴스인지
		System.out.println(circle instanceof Circle);
		// 오류: class는 hierachy 상위와 하위만 instanceof 연산자를 사용할 수 있다.
//		System.out.println(circle instanceof Rectangle);   : 오류 구문
		
		//interface는 hierachy와 상관없이 instanceof 연산자를 사용할 수 있다.
		System.out.println(circle instanceof Drawable); // circle이 Drawable 인터페이스를 구현했는지
		System.out.println(circle instanceof Runnable);// circle이 Runnable 클래스의 인스턴스인지

결과값
true
true
true
true
false

Ch.3-6 예외 처리

예외처리가 유용한 경우

1) 파일을 다루는 경우
해당 파일이 존재하지 않거나 다른 프로세스에 의해 사용중인 경우 예외 발생
2) 입출력을 다루는 경우
이미 닫힌 입출력 스트림에 대해 작업하려 할 경우 예외 발생
3) 네트워크을 통한 데이터 통신
서버나 클라이언트 한 쪽에서 응답이 없는 경우
네트워크 상태가 안 좋아서 정해진 시간동안 데이터를 받지 못하는 경우

사용자 정의 예외

예외의 최상위 클래스인 Exception 클래스를 상속받아 새로운 예외를 정의할 수 있음
일반적으로 생성자만 구현

Ch4 자바 기본 API

        Point p = new Point(10,20);
		
		//Class klass = p.getClass();
		System.out.println(p.getClass()); 	//refrection
		System.out.println(p.hashCode()); 	// address 기반의 해싱값
											// address x
											// reference x
		System.out.println(p.toString());	//getClass() + "@" + hashCode()
		System.out.println(p);

toString 코드

public String toString() {
		return "Point [x=" + x + ", y=" + y + "]";
	}

결과값
class chapter04.Point
1291
Point [x=10, y=20]
Point [x=10, y=20]

.getClass() : 현재 참조하고있는 클래스 확인가능
.hasCode() : address기반의 해싱값 확인

동일성 vs 동질성

동일성 비교 : ==

동질성 비교 : 객체1.equals(객체2)

		Point p1 = new Point(10,20);
		Point p2 = new Point(10,20);
		Point p3 = p2;
		
		// == : 두 객체의 동일성을 비교
		System.out.println(p1 == p2);
		System.out.println(p2 == p3);
		
		// equals : 두 객체의 동질성 비교(내용비교)
		// 부모 클래스 Object의 기본 구현은 동일성(==) 비교와 같다.
		System.out.println(p1.equals(p2));
		System.out.println(p2.equals(p3));

결과
false
true
true
true

Ch4. 1-3 String Class

특수 문자 표현 및 출력

C:\temp 출력
System.out.println("c:\temp");
"hello" 출력
System.out.println("\"hello\"");

string관련 API

		String s1 = "abc";
		String s2 = "def";
		String s3 = s2;
		
		s2 = s1.toUpperCase();
		String s4 =  s2.concat("??");
		String s5 = "!".concat(s2).concat("@");
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s3);
		System.out.println(s4);
		System.out.println(s5);

결과
abc
ABC
def
ABC??
!ABC@

StringBuffer

1.가변크기의 버퍼를 가짐
2. String 객체가 한 번 만들어진 문자열을 수정할 수 없는 것과는 달리 StringBuffer 객체는 수정 가능하다. ( 스트링 버퍼의 크기는 문자열 길이에 따라 가변적으로 변한다)

		//String s1 = "Hello " + "World " + "Java" + 1.8; 이후에 문자열 추가못함
		String s1 = new StringBuffer("Hello ")
		.append("World ")
		.append("Java ")
		.append(1.8)
		.toString();

마지막에 .toString() 붙여주면서 String 자료형으로 변경된다.

0개의 댓글