λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
Java

[Java-기초] μ œλ„€λ¦­ λ©”μ„œλ“œ ν™œμš©ν•˜κΈ°

by μ½”λ”©ν•˜λŠ” λΆ•μ–΄ 2021. 2. 21.
λ°˜μ‘ν˜•

β–Ά μ œλ„€λ¦­ λ©”μ„œλ“œ ν™œμš©ν•˜κΈ°

λ©”μ„œλ“œμ˜ λ§€κ°œλ³€μˆ˜λ₯Ό μžλ£Œν˜• λ§€κ°œλ³€μˆ˜λ‘œ μ‚¬μš©ν•˜λŠ” κ²½μš°μ— λŒ€ν•΄μ„œ μ•Œμ•„λ³΄μž. λ˜ν•œ μžλ£Œν˜• λ§€κ°œλ³€μˆ˜κ°€ ν•˜λ‚˜ 이상인 κ²½μš°λ„ μ‚΄νŽ΄λ³΄μž. μ œλ„€λ¦­ λ©”μ„œλ“œμ˜ 일반 ν˜•μ‹μ€ λ‹€μŒκ³Ό κ°™λ‹€.

λ°˜ν™˜ν˜• μ•žμ— μ‚¬μš©ν•˜λŠ” <μžλ£Œν˜• λ§€κ°œλ³€μˆ˜>λŠ” μ—¬λŸ¬ 개일 수 있으며, μ΄λŠ” λ©”μ„œλ“œ λ‚΄μ—μ„œλ§Œ μœ νš¨ν•˜λ‹€.

​

​

Point.java

package generics;

public class Point<T, V> {
	T x;
	V y;

	Point(T x, V y) {
		this.x = x;
		this.y = y;
	}

	public T getX() {  // μ œλ„€λ¦­ λ©”μ„œλ“œ
		return x;
	}

	public V getY() {  // μ œλ„€λ¦­ λ©”μ„œλ“œ
		return y;
	}
}

 

package generics;

public class GenericMethod {
	public static <T, V> double makeRectangle(Point<T, V> p1, Point<T, V> p2) {
		double left = ((Number) p1.getX()).doubleValue();
		double right = ((Number) p2.getX()).doubleValue();
		double top = ((Number) p1.getY()).doubleValue();    // μ–΄λ–€ μžλ£Œν˜•μ΄ λ“€μ–΄μ˜€λ”λΌλ„ double둜 λ³€ν™˜.
		double bottom = ((Number) p2.getY()).doubleValue(); // Number둜 κ°€μ Έμ™€μ„œ double둜 λ³€ν™˜.

		double width = right - left;
		double height = bottom - top;

		return width * height;
	}

	public <T> void test(T t) { // ν΄λž˜μŠ€μ— μ œλ„€λ¦­μ΄ μ—†μœΌλ―€λ‘œ λ©”μ„œλ“œ μžμ²΄μ— μ •μ˜λ₯Ό ν•΄μ€Œ.
	}                           // λ°˜ν™˜ν˜•μ„ μ“°κΈ° 전에 μ œλ„€λ¦­ νƒ€μž…μ„ μ μ–΄μ€˜μ•Ό ν•œλ‹€. κ·Έλž˜μ•Ό μ œλ„€λ¦­ λ©”μ„œλ“œκ°€ 됨 !

	public static void main(String[] args) {
		Point<Integer, Double> p1 = new Point<Integer, Double>(0, 0.0); // 객체λ₯Ό μƒμ„±μ‹œμΌœμ•Όν•¨
		Point<Integer, Double> p2 = new Point<>(10, 10.0); // 객체λ₯Ό μƒμ„±μ‹œμΌœμ•Όν•¨

		double rect = GenericMethod.<Integer, Double>makeRectangle(p1, p2);
		System.out.println("두 점으둜 λ§Œλ“€μ–΄μ§„ μ‚¬κ°ν˜•μ˜ λ„“μ΄λŠ” " + rect + "μž…λ‹ˆλ‹€.");
	}
}

<μ‹€ν–‰ κ²°κ³Ό>

​GenericMethod ν΄λž˜μŠ€λŠ” μ œλ„€λ¦­ ν΄λž˜μŠ€κ°€ μ•„λ‹ˆλ‹€. μ œλ„€λ¦­ ν΄λž˜μŠ€κ°€ μ•„λ‹ˆλΌλ„ 내뢀에 μ œλ„€λ¦­ λ©”μ„œλ“œλ₯Ό κ΅¬ν˜„ν•  수 μžˆλ‹€. μ œλ„€λ¦­ λ©”μ„œλ“œμΈ makeRectangle( ) λ©”μ„œλ“œλŠ” static으둜 κ΅¬ν˜„ν–ˆλ‹€. makeRectangle( ) λ©”μ„œλ“œμ—μ„œ μ‚¬μš©ν•˜λŠ” T와 VλŠ” makeRectangle( ) λ©”μ„œλ“œ λ‚΄λΆ€μ—μ„œλ§Œ μœ νš¨ν•˜κ²Œ μ‚¬μš©ν•  수 μžˆλ‹€.

λ°˜μ‘ν˜•

λŒ“κΈ€