티스토리 뷰

1. Object클래스의 11개 함수를 나열해 보시오.

Object 클래스란? 모든 클래스의 최상위 클래스이자 부모 클래스이다.

함수명 메소드 용도
equals( ) ★ public boolean equals(Object obj) {   } 객체동등비교 (주소값비교)
hashCode( ) ★ public int hashCode( ) 객체 해시코드 값 리턴
toString( ) ★ public String to String( ) {   } 객체 문자열 정보
clone( )  Shallow
Deep
객체복사 (얕은복사, 깊은복사)
finalize( )  protected void finalize( ) throws Throwable {   } 객체 소멸, jvm이 호출
getClass( ) Class getClass( ) {   } 객체 클래스형 반환
wait( ) public void wait( ) {   } 스레드(thread) 일시중지
wait(long timeout) public void wait(long timeout) {   } 스레드 일시중지
wait(long time out, int nanos) public void wait(long time out, int nanos) {   } 스레드 일시중지
notify( )  public void notify( ) {   } wait된 스레드 재개
notifyall( )  public void notifyall( ) {   } wait된 모든 스레드 재개

 


2. equals 함수에 대하여 설명하시오.

인스턴스의 비교를 원할시 equals 메소드를 사용한다. 해당 메소드 다음에는 object 즉, 8개의 자료형 타입 중 참조형이 올 수 있으며 boolean equals(Object obj) 형태로 적는다. boolean은 true와 false를 판별해 주는 데이터 타입이므로 자기 자신의 객체와 obj하고 주소가 같으면 true, 다르면 false가 된다. 

		class INum {
			private int num;
			public INum(int num) {
				this.num = num;
			}

			@Override
			public boolean equals(Object obj) {
				if (this.num == ((INum) obj).num)
					return true;
				else
					return false;
			}
		}

 

 


3. String 클래스 에서 문자열 비교시 equals를 쓰는 이유는?

A .equals B: 문자열 비교 

     A == B : 주소 비교

    

 


4. shallow copy, deep copy 의 차이는?

Rectangle처럼 참조형이 왔을 때 deep copy가 필요하다. 참조라 객체가 생성된 부분이 있는데 이건 shallow copy시 copy가 안되기 때문이다. 따라서 deep copy는 해당 class가 참조형을 가질 때 필요한 것이다.

Shallow copy

class Point2 implements Cloneable {
	private int xPos;
	private int yPos;

	public Point2(int x, int y) {
		xPos = x;
		yPos = y;
	}

	public void showPosition() {
		System.out.printf("[%d, %d]", xPos, yPos);
		System.out.println();
	}

	public void changePos(int x, int y) {
		xPos = x;
		yPos = y;
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}

}

class Rectangle2 implements Cloneable {
	private Point2 upperLeft; // 좌측 상단 좌표
	private Point2 lowerRight; // 우측 하단 좌표

	public Rectangle2(int x1, int y1, int x2, int y2) {
		upperLeft = new Point2(x1, y1);
		lowerRight = new Point2(x2, y2);
	}

	// 좌표 정보 수정
	public void changePos(int x1, int y1, int x2, int y2) {
		upperLeft.changePos(x1, y1);
		lowerRight.changePos(x2, y2);
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();

	}

	// 직사각형 좌표 정보 출력
	public void showPosition() {
		System.out.println("좌측 상단: ");
		upperLeft.showPosition();

		System.out.println("우측 상단: ");
		lowerRight.showPosition();
		System.out.println();
	}

}

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

		Rectangle org = new Rectangle(1, 1, 9, 9);
		Rectangle cpy;

		try {
			// 인스턴스 복사
			cpy = (Rectangle) org.clone();

			// 한 인스턴스의 좌표정보 수정
			org.changePos(2, 2, 7, 7);
			org.showPosition();
			cpy.showPosition();

			org.changePos(3, 3, 3, 3);
			org.showPosition();
			cpy.showPosition();

		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

	}

}

출력값:

좌측 상단: 
[2, 2]
우측 상단: 
[7, 7]

좌측 상단: 
[1, 1]
우측 상단: 
[9, 9]

좌측 상단: 
[3, 3]
우측 상단: 
[3, 3]

좌측 상단: 
[1, 1]
우측 상단: 
[9, 9]

 

 

Deep copy

class Point3 implements Cloneable {
	private int xPos;
	private int yPos;

	public Point3(int x, int y) {
		xPos = x;
		yPos = y;
	}

	public void showPosition() {
		System.out.printf("[%d, %d]", xPos, yPos);
		System.out.println();
	}

	public void changePos(int x, int y) {
		xPos = x;
		yPos = y;
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}

}

class Rectangle implements Cloneable {
	private Point3 upperLeft; // 좌측 상단 좌표
	private Point3 lowerRight; // 우측 하단 좌표

	public Rectangle(int x1, int y1, int x2, int y2) {
		upperLeft = new Point3(x1, y1);
		lowerRight = new Point3(x2, y2);
	}

	// 좌표 정보 수정
	public void changePos(int x1, int y1, int x2, int y2) {
		upperLeft.changePos(x1, y1);
		lowerRight.changePos(x2, y2);
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		// Object 클래스의 clone 메소드 호출 결과를 얻음
		Rectangle copy = (Rectangle) super.clone();

		// 깊은 복사의 형태로 복사본을 수정
		copy.upperLeft = (Point3) upperLeft.clone();
		copy.lowerRight = (Point3) lowerRight.clone();

		// 완성된 복사본의 참조를 반환
		return copy;

	}

	// 직사각형 좌표 정보 출력
	public void showPosition() {
		System.out.println("좌측 상단: ");
		upperLeft.showPosition();

		System.out.println("우측 상단: ");
		lowerRight.showPosition();
		System.out.println();
	}

}

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

		Rectangle org = new Rectangle(1, 1, 9, 9);
		Rectangle cpy;

		try {
			// 인스턴스 복사
			cpy = (Rectangle) org.clone();

			// 한 인스턴스의 좌표정보 수정
			org.changePos(2, 2, 7, 7);
			org.showPosition();

			
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

	}

}

출력값:

좌측 상단: 
[2, 2]
우측 상단: 
[7, 7]

 


5. 금일 배운 Rectangle의 shallow copy 와 deep copy 일 때의 메모리 그림을 그려보시오.

Shallow copy

 

 

 

 

Deep copy

 

 

 


6. 아래를 프로그래밍 하시오.

- 클래스 Person
* 필드 : 이름, 나이, 주소 선언
- 클래스 Student
* 필드 : 학교명, 학과, 학번, 8개 평균평점을 저장할 배열로 선언
* 생성자 : 학교명, 학과, 학번 지정
* 메소드 average() : 8개 학기 평균평점의 평균을 반환
- 클래스 Person과 Student 
- 프로그램 테스트 프로그램의 결과 : 8개 학기의 평균평점은 표준입력으로 받도록한다.

이름 : 김다정
나이 : 20

주소 : 서울시 관악구
학교 : 동양서울대학교
학과 : 전산정보학과
학번 : 20132222
----------------------------------------

8학기 성적을 입력해 주시기 바랍니다.

1학기 학점  → 3.37
2학기 학점  → 3.89
3학기 학점  → 4.35
4학기 학점  → 3.76
5학기 학점  → 3.89
6학기 학점  → 4.26
7학기 학점  → 4.89
8학기 학점  → 3.89

----------------------------------------

 

출력값:

8학기 총 평균 평점은 4.0375점입니다.

메인 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
public class GPA {
    public static void main(String[] args) {
        Student st = new Student("김다정"20"서울시 관악구""동양서울대학교""전산전보학과"20132222);
        st.printInfo();
        System.out.println();
 
        st.setGpa();
        System.out.println("8학기 총 평균 평점은 " + st.averaege() + "입니다.");
 
    }
 
}
 
cs

부모 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Person {
    private String name, addr;
    private int age;
 
    public Person(String name, int age, String addr) {
        this.addr = addr;
        this.age = age;
        this.name = name;
    }
 
    public void printInfo() {
        System.out.println("이름 : " + name);
        System.out.println("나이 : " + age);
        System.out.println();
        System.out.println("주소 : " + addr);
    }
 
}
 
 
cs

자식 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.Scanner;
 
class Student extends Person {
    private String school, major;
    private int stuID;
 
    private double[] gpa = new double[8];
 
    // 우린 이걸 생성자라 부른다 !
    public Student(String name, int age, String addr, String school, String major, int stuID) {
        super(name, age, addr);
        this.school = school;
        this.major = major;
        this.stuID = stuID;
 
    }
 
    @Override
    public void printInfo() {
        super.printInfo();
        System.out.println("학교 : " + school);
        System.out.println("학과 : " + major);
        System.out.println("학번 : " + stuID);
    }
 
    public double averaege() {
        double sum = 0;
        double avg = 0;
 
        for (double d : gpa) {
            sum += d;
        }
        avg = sum / gpa.length;
        return avg;
    }
 
    public String getSchool() {
        return school;
    }
 
    public void setSchool(String school) {
        this.school = school;
    }
 
    public String getMajor() {
        return major;
    }
 
    public void setMajor(String major) {
        this.major = major;
    }
 
    public int getStuID() {
        return stuID;
    }
 
    public void setStuID(int stuID) {
        this.stuID = stuID;
    }
 
    public double[] getGpa() {
        return gpa;
    }
 
    public void setGpa(double[] gpa) {
        this.gpa = gpa;
    }
 
    public void setGpa() {
 
        try {
            Scanner sc = new Scanner(System.in);
            System.out.println("8학기 성적을 입력해 주시기 바랍니다.");
 
            for (int i = 0; i < gpa.length; i++) {
                System.out.print((i + 1+ "학기 학점 → ");
                gpa[i] = sc.nextDouble();
            }
 
        } catch (Exception e) {
            System.out.println("잘못된 입력입니다. 다시 입력해 주시기 바랍니다.");
            setGpa();// 재귀함수. 에러나면 자기자신 다시 호출
        }
 
    }
 
}
 
 
cs

 

 

 


7.철수 학생은 다음 3개의 필드와 메소드를 가진 4개의 클래스 Add, Sub, Mul, Div를 작성하려고 한다.

- int 타입의 a, b 필드: 2개의 피연산자
- void setValue(int a, int b): 피연산자 값을 객체 내에 저장한다.
- int calculate(): 클래스의 목적에 맞는 연산을 실행하고 결과를 리턴한다.

곰곰 생각해보니, Add, Sub, Mul, Div 클래스에 공통된 필드와 메소드가 존재하므로 
새로운 추상 클래스 Calc를 작성하고, Calc를 상속받아 만들면 되겠다고 생각했다. 
그리고 main() 메소드에서 다음 실행 사례와 같이 2개의 정수와 연산자를 입력받은 후, 
Add, Sub, Mul, Div 중에서 이 연산을 처리할 수 있는 객체를 생성하고 
setValue() 와 calculate()를 호출하여 그 결과 값을 화면에 출력하면 된다고 생각하였다. 

철수처럼 프로그램을 작성하라.(예외처리 구문도 넣어 주세요^^)

두 정수와 연산자를 입력하시오 >> 5 7 +


 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.Scanner;
 
public class Arithmetic {
    public static void main(String[] args) {
 
        Scanner sc = new Scanner(System.in);
        
        System.out.print("두 정수와 연산자를 입력하시오 >>");
        int a = sc.nextInt();
        int b = sc.nextInt();
        String op = sc.next();
 
        Calc cal = null;// 첨엔 null로 선언
 
        switch (op) {
        case "+":
            cal = new Add();
            break;
        case "-":
            cal = new Sub();
            break;
        case "*":
            cal = new Mul();
            break;
        case "/":
            cal = new Div();
            break;
 
        default:
            System.out.println("잘못된 연산자 입력입니다.");
        }
        cal.setValue(a, b); // polymorphism 적용. ab가 딱딱 저장됨
        System.out.println(cal.calculate());
 
    }
}
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
abstract class Calc {
    protected int a, b; //상속할거라서 protected
    void setValue(int a, int b) {
        this.a = a;
        this.b = b;
    }
    abstract int calculate();
}
 
 
 
 
cs

 

1
2
3
4
5
6
7
8
public class Add extends Calc {
    @Override
    int calculate() {
        return super.a + super.b;
    }
 
}
 
cs
1
2
3
4
5
6
7
8
public class Sub extends Calc {
    @Override
    int calculate() {
        return super.a - super.b;
    }
 
}
 
cs
1
2
3
4
5
6
7
8
public class Mul extends Calc {
    @Override
    int calculate() {
        return super.a * super.b;
    }
 
}
 
cs
1
2
3
4
5
6
7
8
public class Div extends Calc {
    @Override
    int calculate() {
        return super.a / super.b;
    }
 
}
 
cs

 

 


8. 문자열을 입력 받아 한 글자씩 회전시켜 모두 출력하는 프로그램을 작성하라.
(클래스로 작성할 필요없이 메인에서 직접 할것)

[Hint] Scanner.nextLine()을 이용하면 빈칸을 포함하여 한 번에 한 줄을 읽을 수 있다.
문자열을 입력하세요. 빈칸이나 있어도 되고 영어 한글 모두 됩니다.

I Love you
Love youI
Love youI
ove youI L
ve youI Lo
e youI Lov
youI Love
youI Love
ouI Love y
uI Love yo
I Love you
```
힌트: Substring 사용

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.Scanner;
 
public class ILoveU {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("문자열을 입력하세요. 빈칸이나 있어도 되고 영어 한글 모두 됩니다.");
        String input = sc.nextLine();
        
        for(int i = 0; i<=input.length(); i++) {
            System.out.print(input.substring(i));
            System.out.println(input.substring(0,i));
        }
        
    }
 
}
 
 
 
cs

 

 


▣오늘의 방과후 실습

문제 1
다음 main()이 실행되면 아래 예시와 같이 출력되도록 MyPoint 클래스를 작성하라

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class MyPoint {
    private int x, y;
 
    public MyPoint(int x, int y) {
        this.x = x;
        this.y = y;
 
    }
 
    @Override
    public String toString() {
 
        return "Point(" + x + "," + y + ")";
 
    }
 
    @Override
    public boolean equals(Object obj) {
        MyPoint point = (MyPoint)obj;
        
        if (this.x == ((MyPoint) obj).x && this.y == ((MyPoint) obj).y)
            return true;
        else
            return false;
    }
 
}
 
public class MyPointTest {
    public static void main(String[] args) {
        MyPoint p = new MyPoint(350);
        MyPoint q = new MyPoint(450);
 
        System.out.println(p);
 
        if (p.equals(q))
            System.out.println("같은 점");
        else
            System.out.println("다른 점");
 
    }
 
}
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   @Override
    public boolean equals(Object obj) {
        MyPoint point = (MyPoint)obj;
        
        if (this.x == ((MyPoint) obj).x  &&  this.y == ((MyPoint) obj).y)
            return true;
        else
            return false;
    }
 
 
//이 부분 비슷한 듯 다르게 현 가능 
 
    @Override
    public boolean equals(Object obj) {
        Circle circle = (Circle)obj;
        
        if( ( this.x == circle.x ) && ( this.y == circle.y ) )
            return true;
        }
            return false;
}
cs

 

 

 

 

 

문제 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Circle{
    private int x, y, radius;
    
    public Circle(int x, int y, int radius) {
        this.radius=radius;
        this.x=x;
        this.y=y;
        
    }
    
    @Override
    public String toString() {
        return "Circle(" + x + "," + y + ")"+ "반지름"+radius;
    }
    
    @Override
    public boolean equals(Object obj){
        if (obj instanceof Circle) {
        
        Circle circle = (Circle)obj;
        
        if( ( this.x == circle.x ) && ( this.y == circle.y ) )
            return true;
        }
            return false;
        
    }
    
    
}
public class CirclePointTest {
    public static void main(String[] args) {
        Circle a = new Circle(235); //중심 (2,3)에 반지름 5인 원
        Circle b = new Circle(2330); //중심 (2,3)에 반지름 30인 원
        
        System.out.println("원 a : " +a);
        System.out.println("원 b : " +b);
        
        if(a.equals(b))
            System.out.println("같은 원");
        else
            System.out.println("서로 다른 원");
 
    }
 
}
 
cs

 

'면접준비 > KOSMO 허쌤 숙제' 카테고리의 다른 글

학습정리-11-02(compareTo)  (0) 2021.11.02
학습정리-11-01  (0) 2021.11.01
학습정리-10-28(Error와 Exception)  (0) 2021.10.28
학습정리-10-27 (사칙연산 계산기)  (4) 2021.10.27
학습정리-10-26  (0) 2021.10.27
댓글