상세 컨텐츠

본문 제목

[java] 상속(Inheritance) 연습문제

java

by ~지우~ 2021. 7. 7. 18:23

본문

728x90

오늘은 「java_an_introduction_to_problem_solving_and_programming_6th_edition」 649페이지 6번 문제를 풀어보겠습니다.

<문제>

출처: java_an_introduction_to_problem_solving_and_programming_6th_edition 

 

Vehicle이라는 상위 클래스(superclass = base class)를 만들고 이 것의 하위 클래스(subclass = derived class)인 Truck 을 만들면 됩니다.

 

public class Vehicle {

	public  String name;
	public int num;
	public Person owner;
	
	Vehicle(String name, int num, Person owner){
		this.name = name;
		this.num = num;
		this.owner = owner;
	};
    
}

 

public class Truck extends Vehicle{
	private double load;
	private double towing;
	
	public Truck(String name, int num, Person owner){
		super(name, num, owner);
	}
	public void setTruck(double load, double towing) {
		this.load = load;
		this.towing = towing;
	}
	public double getLoad() {
		return load;
	}
	public double getTowing() {
		return towing;
	}
	
	public boolean equals(Object o) {
		if(!(o!=null && o instanceof Truck))
			return false;
		Truck t = (Truck)o;
		return (this.load == t.load) &&
				(this.towing == t.towing) &&
				(this.name.equals(t.name)) &&
				(this.num == t.num) &&
				(this.owner == t.owner);
	}
}
public class TruckDemo {

	public static void main(String[] args) {
		Truck d1 = new Truck("Jack", 10, Driver);
		d1.setTruck(2.5, 4);
		System.out.println(d1.getLoad());
		System.out.println(d1.getTowing());
		
		Truck d2 = new Truck("Jack", 4, Driver);
		d2.setTruck(2.5, 4);
		System.out.println(d1.getLoad());
		System.out.println(d1.getTowing());
		System.out.println(d2.equals(d1));
	}

}
728x90

관련글 더보기

댓글 영역