[java]최상위 클래스 object, 형변환

eunu·2024년 1월 29일
0

JAVA

목록 보기
6/21

최상위 클래스, object

모든 클래스는 최상위 클래스가 존재한다.

형변환

자식 → 부모 클래스 형변환

부모의 자료형으로 변환되는 것 = 형변환

자식에서 추가된 메서드와 변수에 접근할 수 없다.

  • RempVO
    public class RempVO extends Employee{
    
    	public RempVO() {
    		super(); // 부모 생성자 호출
    	}
    	
    	public void welcome() {
    		System.out.println("어서옵셔~");
    	}
    }
  • Employee
    package Company;
    
    public class Employee extends Object{
    	
    	// 상속 관계 - 부모클래스 정의 - 멤버변수의 접근제한자 ? --> protected
    	// 사원 정보
    	// 사번, 이름, 나이, 폰, 입사일, 부서, 결혼여부 - T/F  저장
    	// empId, name, age, phone, empDate, dept, marriage
    	
    	
    	// static : empId가 1000번부터 순차적으로 1씩 부여하여 자동으로 사번이 부여되도록 하고 싶음
    	// static 변수는 정적변수로 프로그램 시작부터 끝날 때까지 존재하는 변수
    	// 메모리 공간 - data 영역에 존재함(힙영역에 존재하는 클래스들과는 별개)
    	// stack - 중괄호 안에서 선언된 시점부터, 중괄호가 끝나면 소멸됨 
    	// heep - new 생성자() -->> 이때 인스턴스(객체) 메모리 공간에 할당됨 / 필요 없으면 가비지컬렉터 라는 칭구가 자동으로 회수
    	
    	
    	private static int serial_num = 1000;
    	// 공통으로 사용되는 변수니까 메모리를 낭비할 필요없이 data영역에 존재하는 static변수로 변경
    	private static String company = "korea㈜";
    	
    	protected int empId;
    	protected String name;
    	protected int age;
    	protected String phone;
    	protected String empDate;
    	protected String dept;
    	protected boolean marriage;
    	
    	public Employee() {
    		super(); // new Object(); -> Object 생성자 호출
    	}
    	public Employee(String name, int age) {
    		this.empId = ++serial_num;
    		this.name = name;
    		this.age = age;
    	}
    	
    	@Override
    	public String toString() {
    		return company +"/"+ empId + "/" + name + "/" + age;
    	}
    	
    }
//Test.java
RempVO em1 = new RempVO();
		Employee em2 = new RempVO();
		Object em3 = new RempVO();
		
		em1.welcome();
//		em2.welcome(); // 접근 불가능
//		em3.welcome(); // 접근 불가능

캐스팅

업캐스팅

업캐스팅
// 인스턴스 연결을 바꿔줌.

자료형이 부모인 Animal로 변환되었기 재문에, 자식에서 추가된 메서드와 변수를 사용할 수 없음.

다운캐스팅

자식의 유형으로 형변환

  • 코드 예시
    ani.eat();
    		
    		ani = new Cat(); // cat 인스턴스 생성해서, 동물을 바꿔준다.
    		// 업캐스팅
    		// 인스턴스 연결을 바꿔줌.
    		
    		ani.eat();
    		
    		// ani.sound();// 자료형이 부모인 Animal로 변환되었기 재문에, 자식에서 추가된 메서드와 변수를 사용할 수 없음.
    		
    		Cat c = (Cat)ani; // 자식의 유형(Cat)으로 형변환 시켜줘야 한다. : 다운캐스팅
    		c.sound();

instanceof : a instanceof b / a가 b로 만들어진 객체 맞니?

조건문 기반 다운캐스팅된 객체 실행

for(Animal ani : aniList) {
			System.out.println("----------------");
			
			
			if (ani instanceof Human) { // instanceof : a instanceof b / a가 b로 만들어진 객체 맞니?
				Human h = (Human)ani; // Human 이면 다운캐스팅
				h.run();
			}else if( ani instanceof Eagle) {
				Eagle e = (Eagle)ani;
				e.flying();
			}else if( ani instanceof Tiger) {
				Tiger t = (Tiger)ani;
				t.hunting();
			}
			ani.eat();
			
			
		}

클래스 자동 형변환

특징

  1. 오버라이딩한 메서드는 클래스 타입변환(형변환)을 했어도 자식메서드 호출
  2. 클래스 타입 변환을 한 클래스는, 자식클래스만의 멤버변수와 메서드 호출 불가능
    1. 그럼 더 이상 자식 메서드나 변수를 호출할 수 는 없을까?
      1. 인스턴스 유형을 검사하는 instanceof를 이용해 자식 메서드로 만든게 맞으면 다운캐스팅을 이용해 호출한다.
profile
Just Do It

0개의 댓글