본문으로 바로가기

다형성 (Polymorphism)

category onYouTube/Java 2021. 3. 24. 17:53
  • "다형성 (Polymorphism)" : 하나의 메소드나 클래스가 다양한 방법으로 동작하는 것
class A {}
class B extends A {}


public class PolymorphismDemo1 {

	public static void main(String[] args) {
    
		A obj = new B();
		// A에 정의된 메소드를 실행하면 오버라이딩 된 B의 메소드들이 실행됨
		// B에만 정의된 메소드를 실행하면 에러가 발생함
	}
}
interface I {}

class C implements I {}


public class PolymorphismDemo2{

	public static void main(String[] args) {

		I obj = new C();
	}
}
interface father {}
interface mother {}
interface programmer { public void coding(); }
interface believer{}


class Steve implements father, programmer, believer {

	public void coding() {
    
		System.out.println("fast");
	}
}


class Rachel imeplments mother, programmer {

	public void coding() {
    
		System.out.println("elegance");
	}
}


public class Worksapce {

	pulic static void main(String[] args){
    
		programmer employee1 = new Steve();
		programmer employee2 = new Rachel();

		employee1 coding();
		employee2 coding();
	}
}
interface I2 {

	public String A();
}


interface I3 {

	public String B();
}


class D implements I2, I3 {

	public String A() { return "A"; }
    
	public String B() { return "B"; }
}


public class PolymorphismDemo1 {

	public static void main(String[] args) {
    
		D obj = new D();
		I2 objI2 = new D();
		I3 objI3 = new D();
		
		obj.A();
		obj.B();
		
		objI2.A();
		objI2.B(); // 에러
		
		objI3.A(); // 에러
		objI3.B();
	}
}

'onYouTube > Java' 카테고리의 다른 글

Object 클래스  (0) 2021.03.26
예외  (0) 2021.03.26
인터페이스 (Interface)  (0) 2021.03.24
final  (0) 2021.03.24
추상 (Abstract)  (0) 2021.03.24