https://velog.io/@foeverna/Java-인터페이스-인터페이스를-활용한-다형성-구현Polymorphism in inheritance 프

다형성은 하나의 객체가 여러가지 타입을 가질 수 있는 것을 말합니다.

부모 클래스 타입의 참조 변수로 자식 클래스 타입의 인스턴스를 참조할 수 있도록 할 수 있습니다.

부모 타입의 형태로 자식 객체의 행위를 하는 것.

package Day15.Ex02_Poly02;

// Superclass
public class Student {
...
	public void calcScore(Student st) {
	// 한개의 메소드로 계속해서 사용
		if (st instanceof University)
			System.out.println("University Calculation");
		else if (st instanceof Elementary)
			System.out.println("Elementary Calculation");
		// 코드가 늘어나는것 같지만 실행되는것은 하나
	}
}
/////////////////////////////////////////////////////////////////

//Subclass
public class University extends Student {
	...
	// 학점을 출력하는 메서드
	public int getCourses() {
		return courses;
	}
	
	@Override
	public String getStudInfo() { // 학생의 신상정보를 출력해 주는 메서드
		System.out.println("Student 클래스의 getStudInfo( ) 호출");
		return "이름: " + name + ",학년: " + grade + ",학점: " + getCourses();
	}
}
/////////////////////////////////////////////////////////////////

// Main
public class StudentTest {
	public static void main(String[] args) {
		
		Student u = new University("Hong", 3, 23);
		u.calcScore(u);
		// Student 타입을 가지고 University instance 생성
		Student e = new Elementary("Park", 2, 19);
		e.calcScore(e);
		
		// Downcasting
		// package Day15.Ex01_Poly;
		University u = (University) s;
		System.out.println("score: " + u.getCourses());
	}
}

상속에서 복잡해지지 않기 위해 쓰는 것!

Superclass에 매소드 추가 없이 해당 메소드를 쓰기 위해 업캐스팅으로 다른 타입으로 생성, 하지만 자식생성자에만 있는 메소드를 사용하기 위해서는 다운캐스팅이 필요하다.

Downcasting

// Downcasting
Child child = (Child) parent;

Upcasting

Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature.

Casting

Type cating is when you assign a value of one primitive data type to another type

public class Casting {
	public static void main(String[] args) {
		
		/**
		 *  Widening Casting
		**/
		int myInt = 9;
		double myDouble = myInt; 
		// Automatic casting from "Int" to "Double"
		
		System.out.println(myInt);
		// Output 9
		System.out.println(myDouble);
		// Output 9.0
		
		/**
		 *  Narrowing Casting
		**/
		double yourDouble = 9.79;
		int yourInt = (int) yourDouble;
		// Manual casting from "Double" to "Int"
		
		System.out.println(yourDouble);
		// Output 9.79
		System.out.println(yourInt);
		// Output 9
	}
}

Instanceof

public class Student {
...
	public void calcScore(Student st) {
		if (st instanceof University)
			System.out.println("University Calculation");
		else if (st instanceof Elementary)
			System.out.println("Elementary Calculation");
		// 코드가 늘어나는것 같지만 실행되는것은 하나!
	}
}