본문 바로가기

Backend/Java

[인프런] 다형성, 클래스, 호출

예제로 공부하는 Java 100 문제풀이 Part.4

 

class Person{
	String str1 = "난 부모 클래스";
	void method1() {
		System.out.println("에이에이에이");
	}
	void ppp() {
		System.out.println("ppp");
	}
}
class Student extends Person{
	String str2 = "난 자식 클래스";
	void method1() {
		System.out.println("오버라이딩 - AAA");
	}
	void sss() {
		System.out.println("sss");
	}
	void x() {
		method1();
		super.method1();
	}
}

public class Java100_Ex39{
	public static void main(String[] args) {
		// [1]: 객체 생성 --> 부모 + 자식 클래스의 모든 자원을 다 쓸 수 있다.
		Student s1 = new Student();
		System.out.println(s1.str1);
		System.out.println(s1.str2);
		s1.method1();
		s1.sss();
		s1.ppp();
		s1.x();
		System.out.println("===============================");
		
		// 자식 클래스에서 오버라이딩된 부모 클래스의 원본 메서드를 호출하고 싶다면? --> super 키워드 사용
		
		// [2]: 객체 생성 --> 범위는 부모의 자원만을 쓸 수 있다.
		Person s2 = new Student();
		System.out.println(s2.str1);
		s2.ppp(); // ppp
		s2.method1(); // 오버라이딩 - AAA --> 오버라이딩 한 거는 자식의 메서드로 실행.
		((Student)s2).sss();
		System.out.println("===============================");
		
		// 자식의 메서드를 바로 호출하고 싶다면? --> 캐스트 필요
		
		// [3]: 객체 생성 --> 
		Person p1 = new Person();
		p1.method1(); // 에이에이에이
		
		System.out.println("===============================");
		
		// [4]: 객체 생성 --> 
		// Student p2 = new Person();
	}
}