[JAVA] 52. Object & Generic

문정준's avatar
Feb 18, 2025
[JAVA] 52. Object & Generic
모든 클래스의 부모 (생략되어 있음)

1. 타입 일치

Downcasting : instanceof
package ex17; class Dog { String name = "강아지"; } class Cat { String name = "고양이"; } public class Ob01 { static void callName(Object u) { // Downcasting : 메모리에 Dog 클래스가 있는지 먼저 확인 후 실행 // 체크 없이 실행 시 Runtime Error 발생 if (u instanceof Dog) { Dog d = (Dog) u; System.out.println(d.name); } else if (u instanceof Cat) { Cat c = (Cat) u; System.out.println(c.name); } } public static void main(String[] args) { callName(new Dog()); callName(new Cat()); } }
Generic : 힙(heap)에서 (new할 때) 자료형 결정
package ex17; // 여러 자료형을 저장하고 싶을 때 // 1. Object 형 사용 // 2. Generic 사용 : new 할 때 결정 class Box<T> { T data; } public class Ge01 { public static void main(String[] args) { // <> 안에 타입을 적어 지정 // 따로 정해주지 않으면 Object 형으로 설정 Box<String> b = new Box(); b.data = "Hello"; System.out.println(b.data); Box<Integer> i = new Box(); i.data = 10; System.out.println(i.data); } }
 

2. Object 메서드 활용

Share article

sxias