Quiz) 상속/인터페이스 약수 구하기

작업 내용



인터페이스

package pack_Yaksu;

public interface Yaksu {

	public abstract void mtdYaksu();
}



메인클래스

package pack_Yaksu;

public class ExamJava {
	
	//여기에 만들면 필드
	
	public static void main(String[] args) {
		
		//여기에 만들면 지역변수
        
		int rndValParam = (int)(11*Math.random()+10);      
		System.out.println("생성된 랜덤 값 : " + rndValParam);
		
		System.out.println();
		YaksuList objSuper = new YaksuList(rndValParam);
		objSuper.mtdYaksu();

		System.out.println();
		YaksuSum objSub = new YaksuSum(rndValParam);
		objSub.mtdYaksu();
		
	}

}



슈퍼클래스

package pack_Yaksu;

public class YaksuList implements Yaksu {

	private int rndNum;

	public YaksuList(int rndNum) {
		this.rndNum = rndNum;
	}
	
	@Override
	public void mtdYaksu() {
		
		System.out.println("약수");
		for (int i = 1; i <= rndNum; i++) {
			if (rndNum % i == 0) {
				System.out.print(i + "  ");
			}
		}
		System.out.println();
	}
	
	public int getRndNum() {
		return rndNum;
	}
}



서브클래스

package pack_Yaksu;

public class YaksuSum extends YaksuList {

	public YaksuSum(int rndNum) {
		super(rndNum);
	}

	@Override
	public void mtdYaksu() {

		int sum = 0;

		for (int i = 1; i <= super.getRndNum(); i++) {
			if (super.getRndNum() % i == 0) {
				sum += i;
			}
		}
		System.out.println("약수의 합 : " + sum);
	}
}



결과

좋은 웹페이지 즐겨찾기