[220927] 다형성

황준하·2022년 9월 27일
0

◆다형성

▶업캐스팅 ,다운캐스팅

처음에
Shape shape = new Circle() 로
부모에 Circle을 넣어줬었기 떄문에
다시
Circle circle = (Circle) shape; 가 가능하다.
미리 자식으로 메모리에 올라가 있기 때문에

◆인터페이스

▶추상클래스란?

  1. abstract가 먼저 함수에 붙음
  2. 클래스에도 abstract를 붙임
  3. 추상 클래스를 상속받으면 추상메소드를 구현하여야 한다.
  4. 추상클래스 = 자식이 구현하라
  • 추상클래스라 하더라도 추상메소드가 아닌 보통의 메소드도 가질 수 있다.
  • 추상 메소드를 하나라도 가지고 있다면 추상클래스가 된다. 이때엔 class앞에 abstract를 붙여야 한다.

  • 추상메소드로 정의되면 자식클래스에서 반드시 오버라이드 하여야 한다. 하지 않으면 오류가 발생한다.
  • 일반 메소드로 정의되면 자식 클래스에서 오버라이드 하지 않아도 컴파일러가 체크할 방법이 없다.

▶interface

  • 인터페이스 상속괕계가 아닌, 클래스간 유사성을 인코깅
  • 협업관계(외주)의 특효약
  • interface는 다형성에 도움이 된다.
  • interface = 약속 = 강제 = 표준
package java_0926;

interface Printable{
	public void print(String doc);
}

class Printer implements Printable {
	public void print(String doc) {
		System.out.println(doc);
	}
}
public class EmployeeTest {

	public static void main(String[] args) {
		Printable prn = new Printer();
		prn.print("Hello");
	}

}
  1. 인터페이스 정의는 예전 클래스 자리에 오는 자리
  2. 메소드의 몸체가 없다. 추상함수만 가질수 있다.
  3. 객체 생성 불가 ~~ 참조변수 선언만 가능
  4. 추상 메소드가 있으니, 자식이 구현 해야 함. 키워드는 implements

▶추상클래스 계산기

package java_0926;

import java.util.Scanner;

abstract class Calc {
	protected int a, b;

	void setValue(int a, int b) {
		this.a = a;
		this.b = b;
	};

	abstract int calculate();
}

class Add extends Calc {

	@Override
	int calculate() {

		return super.a + super.b;
	}

}

class Sub extends Calc {

	@Override
	int calculate() {

		return super.a - super.b;
	}

}

class Div extends Calc {

	@Override
	int calculate() {

		return super.a / super.b;
	}

	double calculate2() {
		return super.a / (double) super.b;
	}

}

class Mul extends Calc {

	@Override
	int calculate() {

		return super.a * super.b;
	}

}

public class EmployeeTest {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		System.out.print("두 정수와 연산자를 입력하시오>>");
		int a = sc.nextInt();
		int b = sc.nextInt();
		char c = sc.next().charAt(0);

		Calc cal;

		if (c == '+')
			cal = new Add();

		else if (c == '-')
			cal = new Sub();

		else if (c == '/')
			cal = new Div();

		else
			cal = new Mul();

		cal.setValue(a, b);
		System.out.println(cal.calculate());
	}

}

▶ 인터페이스 원그리기

package java_0926;

import java.util.Scanner;

interface Shape {
	final double PI = 3.14; // 상수

	void draw(); // 도형을 그리는 추상 메소드

	double getArea(); // 도형의 면적을 리턴하는 추상 메소드

	default public void redraw() { // 디폴트 메소드
		System.out.print("--- 다시 그립니다.");

		draw();
	}
}

class Circle implements Shape {
	int radius;

	public Circle(int radius) {
		this.radius = radius;
	}

	@Override
	public void draw() {
		System.out.println("원을 그립니다.");

	}

	@Override
	public double getArea() {
		return radius * radius * PI;
	}

}

public class EmployeeTest {

	public static void main(String[] args) {
		Shape donut = new Circle(10); // 반지름이 10인 원 객체
		donut.redraw();
		System.out.println("면적은 " + donut.getArea());

	}

}

▶ null

  • 가비지 콜렉터로 하여금 해당 메모리를 회수해도 좋다는 의미

◆ 과제

▶ 선택정렬

public static int[] selectionSort(int[] arr) {
		for (int i = 1; i < arr.length; i++) {
			int tmp = arr[i], j;
			for (j = i - 1; j >= 0; j--) {
				if (tmp < arr[j]) {
					arr[j + 1] = arr[j];
				} else {
					break;
				}
			}
			arr[j + 1] = tmp;
		}
		return arr;
	}

▶ 스택

package java_0926;

import java.util.Scanner;

interface Stack{
	
    public boolean isEmpty();
    public boolean isFull();
    public void push(char item);
    public char pop();
    public char peek();
    public void clear();
    public void printStack();
}

class StackFunc implements Stack {
	int top;
	char[] stack;
	
	public StackFunc(int stackSize) {
		stack = new char[stackSize];
		top = -1;
	}

	@Override
	public boolean isEmpty() {
		if(top == -1)
			return true;
		else
			return false;
	}

	@Override
	public boolean isFull() {
		if(top == stack.length)
			return true;
		else
			return false;
	}

	@Override
	public void push(char item) {
		if(isFull())
			System.out.println("Stack is Full");
		else {
			stack[++top] = item;
			System.out.println("입력된 문자 : " + item);
		}
		
		
	}

	@Override
	public char pop() {
		if(isEmpty()) {
			System.out.println("Stack is Empty");
			return 0;
		}
		else {
			System.out.println("삭제된 문자 : " + stack[top]);
			return stack[top--];
		}
			
	}

	@Override
	public char peek() {
		if(isEmpty()) {
			System.out.println("Stack is Empty");
			return 0;
		}
		else {
			System.out.println("엿볼려는 문자 : " + stack[top]);
			return stack[top];
		}
			
	}

	@Override
	public void clear() {
		if(isEmpty()) {
			System.out.println("Stack is Empty");
		}else {
			top=-1;
			System.out.println("스택이 초기화 되었습니다.");
		}
		
	}

	
	public void printStack() {
		System.out.print("Stack elements : ");
		for (int i=0; i<=top; i++) {
			System.out.print(stack[i]+" ");
		}
		System.out.println();
	}
	
}

public class EmployeeTest {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("스택 사이즈를 입력하시오.");
		int stackSize = sc.nextInt() ;
		
		Stack stack = new StackFunc(stackSize);

		stack.push('A');
		stack.printStack();

		stack.push('B');
		stack.printStack();

		stack.push('C');
		stack.printStack();

		stack.pop();
		stack.printStack();

		stack.pop();
		stack.printStack();

		stack.peek();
		stack.printStack();

		stack.clear();
		stack.printStack();

	}

}

0개의 댓글