01. Java (v)
02. git
03. Database
04. Jsp [Server]
05. 미니프로젝트 (3W)
06. HTML,CSS
07. JS
08. SpringFramework , SrpingBoot
09. React JS [Front-end]
10. 중간프로젝트 (1M)
11. Linux 명령어
12. AWS 클라우드
13. DevOps - Docker
14. App - Android
15. 최종프로젝트 (1M)
부모클래스 변수 = new 자식클래스()
public class Parent {
public void method01() {
System.out.println("부모의 1번 메서드 실행");
}
public void method02() {
System.out.println("부모의 2번 메서드 실행");
}
}
public class Child extends Parent{
@Override
public void method02() {
System.out.println("자식에 재정의 된 2번 메서드 실행");
}
public void method03() {
System.out.println("자식의 3번 메서드 실행");
}
}
public class MainClass {
public static void main(String args[]) {
Child c = new Child();
c.method01(); // 상속받은 메서드
c.method02(); // 오버라이드 메서드
c.method03(); // 자식의 메서드
System.out.println("----다형성 적용-----");
Parent p = c; // 일시적으로 Parent형으로 형변환
System.out.println("주소값:"+c);
System.out.println("주소값:"+p);
p.method01();
p.method02();
//p.method03(); // x
/*
* 다형성이 적용되면, 본래 멤버에 접근 할 수 없음
* 단, 오버라이드 된 메서드는 정상적으로 호출 됨
*/
}
}
강제 타입 변환(Type Casting)
public class MainClass{
public static void main(String args[]){
Parent p = new Child();
// Child c = (Child)new Parent(); // Class Cast 오류 발생
Child c = (Child)p; // 실행 O
c.method03();
}
}
public class HeteroCollectionExample{
public static void main(String args[]){
Person[] pArr = new Person[4];
// 부모 타입 배열에 자식 객체가 저장될 수 있음
pArr[0]=new Person("홍길동",20);
pArr[1]=new Student("박진수",17,"201600001");
pArr[2]=new Teacher("고길동",22,"Java");
pArr[3]=new Employee("허헌정",23,"교무처");
}
}
// 매개변수에 객체를 전달하려면 타입의 클래스 타입을 적어주면 됨
// 이떄 Person의 자식 클래스는 전부 전달 될 수 있음
publis static void printPersonInfo(Person p){
System.out.println("-----");
System.out.println(p);
}
instanceof
연산자의 왼쪽 항의 객체가 오른쪽 항 클래스의 인스턴스가 맞으면 true, 아니면 false를 리턴public static void main(String args[]) {
Person hong = new Student("홍길동",10,"123");
Person park = new Teacher("박찬호",20,"체육");
Person choi = new Employee("창민",30,"가수");
printPerson(hong);
printPerson(park);
printPerson(choi);
}
public static void printPerson(Person p) {
//p가 Student였으면 Student캐스팅
//p가 Teacher였으면 Teacher캐스팅
if(p instanceof Student) { // p가 student였으면 true
Student s =(Student)p;
System.out.println("p는 원래 Student");
System.out.println(s.info());
}
else if(p instanceof Teacher) {
Teacher t=(Teacher)p;
System.out.println("p는 원래 Teacher");
System.out.println(t.info());
}
else if(p instanceof Employee) {
Employee e = (Employee)p;
System.out.println("p는 원래 Employee");
System.out.println(e.info());
}
}