[Java] Car 객체 다형성

Jeini·2022년 10월 30일
0

📌 Code list

목록 보기
20/55
post-thumbnail
//이동위치
class Point {
	private int x;
	private int y;
	
	public Point(int x, int y) {
		setX(x);
		setY(y);
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}
	
	public String toString() {
		return x + ", " + y;
	}
}
//엔진 부품
class Engine {
	private int cc;
	private int ps;
	
	public Engine(int cc, int ps) {
		setCc(cc);
		setPs(ps);
	}

	public int getCc() {
		return cc;
	}

	public void setCc(int cc) {
		this.cc = cc;
	}

	public int getPs() {
		return ps;
	}

	public void setPs(int ps) {
		this.ps = ps;
	}
	
	public void startEngine() {
		System.out.println("시동을 겁니다.");
	}
	
	public String toString() {
		return cc + "cc, " + ps + "ps";
	}
}
//차 
class Car {
	private String maker;
	private int price;
	private Engine engine; // has - a
	private Point location;// has - a
	
	public Car(String maker, int price, Engine engine, Point location) {
		setMaker(maker);
		setPrice(price);
		setEngine(engine);
		setLocation(location);
	}
	
	public void drive(Point goal) {
		setLocation(goal);
		System.out.println(goal + "로 이동합니다.");
		engine.startEngine();
		
	}
	@Override
	public String toString() {
		String info = "maker: " + maker + "\n";
		info += "price: " + price + "\n";
		info += "engine: " + engine + "\n";
		info += "location: " + location + "\n";
		return info;
		
	}

	public String getMaker() {
		return maker;
	}

	public void setMaker(String maker) {
		this.maker = maker;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	public Engine getEngine() {
		return engine;
	}

	public void setEngine(Engine engine) {
		this.engine = engine;
	}

	public Point getLocation() {
		return location;
	}

	public void setLocation(Point location) {
		this.location = location;
	}
	
	
}
class ElectricCar extends Car {
	public ElectricCar(String maker, int price, Engine engine, Point location) {
		super(maker, price, engine, location);
	}
	@Override
	public String toString() {
		return "전기차\n" + super.toString();
	}
}



public class UseCar {

	public static void main(String[] args) {
		Car c = new Car("Benz",1000000000, new Engine(5000, 400), new Point(0, 0));
		c.drive(new Point(100, 100));
		System.out.println(c);
		ElectricCar e = new ElectricCar("밴츠", 1000000000, new Engine(5000, 400),new Point(10, 10) );
		System.out.println(e);
	}

}
profile
Fill in my own colorful colors🎨

0개의 댓글