관리 메뉴

nkdk의 세상

자바 Language 7일째 본문

My Programing/JAVA

자바 Language 7일째

nkdk 2008. 3. 8. 01:06
package inh;

public class PolyCar {
protected int sp=2;
public void show() {
System.out.println("자동차야...");
}
public int speed() {
return sp;
}

}

package inh;

public class PolyBus extends PolyCar{
private int passenger=3;
public PolyBus(){
}

public void show() {
System.out.println("버스");
}
public void move() {
System.out.println("승객: "+passenger+" 속도: "+ sp);
}
}

package inh;

public class polyMain {
public static void main(String[] args) {
PolyCar car1=new PolyCar();
PolyBus bus1=new PolyBus();
PolyCar car2=new PolyBus(); // 이건 가능 위에 것과 타입이 다르다.
// PolyBus bus2=new PolyCar(); // 이건 안된다. 자식의 이름으로 부모를 부르기 때문이다.

System.out.println(car1+ " " + bus1 + " " +car2);
car1.show();
System.out.println(car1.speed());
bus1.show();
System.out.println(bus1.speed());
// car1.move();
bus1.move();

System.out.println("----------------");
car2.show(); // 부모 객체 변수로 자식의 멤버 호출
// car2.move(); 이건 되지 않는다.

PolyCar car3=new PolyBus();
PolyBus bus2=(PolyBus)car3;
bus2.show();
bus2.move();

// PolyBus bus3=(PolyBus)car1;

System.out.println("---------------");
PolyCar p[]=new PolyCar[3];
p[0]=car1;
p[1]=bus1;
p[2]=car2;
for(int i=0;i<p.length;i++) {
p[i].show();
}
}
}

// 추상 메소드에 대하여 이야기 하겠습니다. 바디가 없는 걸로 만들어 버린다.
// 282P 는 바디가 없는 메소드를 추상 메소드 라고 한다. New 가 안된다. 오버라이딩 하고 New하는 것이다.
// abstract public void print();
// 프로램을 짤 때 강제성을 주기 위해서 만들어 진 것이다.
// 추상 클래스도 가능하다.

package inh;

abstract public class Ship { // 추상 클래
int ship;
abstract public int move(); // 추상 메소드 : 사람을 나르는
public abstract int carry(); // 추상 메소드 : 무기를 나르는
public void print(){
System.out.println("배: 추상 클래스 입니다.");
}
}


package inh;

public class ShipMain {
public static void main(String[] args) {
// Ship sh=new Ship(); // 에러가 된다 추상 클래스 이기 때문에 안된다.
boat boat=new boat();
System.out.println(boat.name()+ " "+ boat.move() +" "+boat.carry());

Ship ship1=new boat();
Cruise cruise=new Cruise();
System.out.println(cruise.name()+ " "+ cruise.move() +" "+cruise.carry());
Ship ship2=new Cruise();
System.out.println(ship1.move() + " "+ ship1.carry());
System.out.println(ship2.move() + " "+ ship2.carry());
System.out.println("---------------------------");
Shiputil.search(ship1);
Shiputil.search(ship2);
}


}




package inh;

public class Cruise extends Ship {
public String name(){
return "전함 무궁화 ";
}
public int move() {
return 300;
}
public int carry() {
return 600;
} // abstarct 를 한 이후 에러 메시지가 없어진다.
} // abstract를 지정한 것에 대해서는 꼭 사용해야 상속이 된다.


package inh;

public class Shiputil {
public static void search(Ship s) {
System.out.println(s.move());
System.out.println(s.carry());
// instaceof 두 객체 타입을 비교 하는 연산자 같으면 true 틀리면 false 을 나오게 한다.
if(s instanceof boat){
System.out.println("보트작업");
boat b=(boat)s;
System.out.println("Boat 이름:"+b.name());
}else if(s instanceof Cruise){
System.out.println("전함작업");
Cruise b=(Cruise)s;
System.out.println("Boat 이름:"+b.name());
}

}
}

// 추상 클래스를 이용한 관련..

자 문제를 풀어 봅시다.~