ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 클래스 상속 & toString재정의 & 다형성
    개발노하우/Java 2007. 5. 14. 12:37

    // 클래스 상속
    class GG{
     public void aaa(){
      System.out.println("GG");
     }
    }

    class JJ extends GG{
     public void aaa(){
      super.aaa();
      System.out.println("JJ");
     }
    }

    public class object{
     public static void main(String arg[]){
      JJ jp = new JJ();
      jp.aaa();
     }
    }

    ================================================================================
    // toString() 재정의
    class KK extends Object{
     public String toString()   
        {
                return this.getClass().getName();
     }
    }
    public class object{
     public static void main(String arg[]){
      KK kp = new KK();
      System.out.println("kp =" + kp); // kp.toString();
     }
    }

    ================================================================================
    // 다형성
    class TT{
     protected int x = 100;
    }

    class RR extends TT{
     int y = 300;
    }

    class WW extends TT{
     int z = 400;
    }

    public class object{
     public static void main(String arg[]){
      TT rp = new RR();
      System.out.println("rp.x =" + rp.x);
      //System.out.println("rp.y =" + rp.y);
     
      TT wp = new WW();
      System.out.println("wp.x =" + wp.x);
      //System.out.println("wp.z =" + wp.z);
     }
    }

    ================================================================================
    // 다형성 [ 배열 ]
    class TT{
     protected int x = 100;
    }

    class RR extends TT{
     int y = 300;
    }

    class WW extends TT{
     int z = 400;
    }

    public class object{
     public static void main(String arg[]){
      TT rp[] = new TT[2];
      rp[0] = new RR();
      rp[1] = new WW();
     
      for(int i=0;i<rp.length;i++)
       System.out.println("rp.x =" + rp[i].x);
     }
    }

    ================================================================================
    // 다형성
    class FF{
     public void aaa(){
      System.out.println("AAA");
     }
     public void bbb(){
      System.out.println("BBB");
     }
    }

    class HH extends FF{
     public void bbb(){
      System.out.println("CCC");
     }
     public void ccc(){
      System.out.println("DDD");
     }
    }

    public class object{
     public static void main(String arg[]){
      FF fp = new FF();
      HH hp = new HH();
      hp.aaa();
      hp.bbb();
      hp.ccc();

      FF ap = new HH();
      ap.aaa();
      ap.bbb();
      //ap.ccc();
     }
    }

    //

Designed by Tistory.