-
Q1
class Calculator { int value; Calculator(){ this.value = 0; } void add(int val){ this.value += val; } void minus(int val){ this.value -= val; } int getValue() { return this.value; } } public class Sample{ public static void main(String[] args){ Calculator cal = new Calculator(); cal.add(10); cal.minus(3); System.out.println(cal.getValue()); } }
Q2 만약 객체변수가 100보다 큰값이될경우 100으로 제한하는 클래스 MaxLimitCalculator
Calculator의 add메소드를 오버라이딩하여 재정의하였음,, 이렇게 되면 MaxLimitCalculator로 만든 객체는 재정의된 add메소드를 사용하게된다.
class Calculator { int value; Calculator(){ this.value = 0; } void add(int val){ this.value += val; } void minus(int val){ this.value -= val; } int getValue() { return this.value; } } class MaxLimitCalculator extends Calculator { void add(int val){ this.value += val; if (this.value > 100) { this.value = 100; } }} public class Sample{ public static void main(String[] args){ MaxLimitCalculator cal = new MaxLimitCalculator(); cal.add(50); cal.add(60); System.out.println(cal.getValue()); } }
Q3 홀짝 판별
class Calculator { int value; Calculator(){ this.value = 0; } void add(int val){ this.value += val; } void minus(int val){ this.value -= val; } int getValue() { return this.value; } boolean isOdd(int val){ if (val % 2 == 0) { return false; } else{ return true; } } } } public class Sample{ public static void main(String[] args){ Calculator cal = new Calculator(); System.out.println(cal.isOdd(3)); System.out.println(cal.isOdd(4)); } }
Q4. 평균값을 구하는 메소드
import java.util.ArrayList; import java.util.Arrays; class Calculator { int value; Calculator(){ this.value = 0; } int getValue() { return this.value; } int avg(int[] data) { int sum=0; for (int i = 0; i < data.length; i++) { sum += data[i]; } return sum / data.length; } int avg(ArrayList<Integer> data) { int sum =0; for (int i = 0; i < data.size(); i++) { sum += data.get(i); } return sum / data.size(); } } public class Sample{ public static void main(String[] args){ int[] data = {1, 3, 5, 7, 9}; ArrayList<Integer> data2 = new ArrayList<>(Arrays.asList(1,3,5)); Calculator cal = new Calculator(); int result = cal.avg(data); int result2 = cal.avg(data2); System.out.println(result); System.out.println(result2); } }
Q5 리스트와 객체
객체생성은 new키워드를 사용한다.
ArrayList<Integer> a = new ArrayList<>(Arrays.asList(1,2,3)); ArrayList<Integer> b= a; a.add(4)
위 예에서 a객체는 1,2,3을 갖는 리스트이다. 리스트b는 새 객체를 생성한것이아닌 a가참조하는 리스트객체를 그대로 참조한다.
그렇기때문에 둘은 동일한 객체로 볼수있다 a==b true 여기서 a가참조하는 리스트객체에 4를 추가하고 b.size()를 출력하면 a,b는 동일한객체이므로 4를 출력한다.
만약 독립적으로 작용하게만들고싶다면 b도 new키워드를 통해선언하면된다.
Q6.
class Calculator { Integer value; void add(int val) { this.value += val; } // Calculator(){ // this.value = 0; // } ->초기화해주는 생성자 public Integer getValue() { return this.value; } } public class Sample{ public static void main(String[] args){ Calculator cal = new Calculator(); cal.add(3); //오류발생 System.out.println(cal.getValue()); } }
오류가 발생하는 이유는 value값을 초기화하지 않고, 더할려고하기때문에
해결하기 위해서는 value field를 초기화하는 생성자를 만드는것
Q7
interface Mineral { int getvalue(); } class Gold implements Mineral{ public int getvalue(){ return 100; } } class Silver implements Mineral{ public int getvalue(){ return 90; } } class Bronze implements Mineral{ public int getvalue(){ return 80; } } class MineralCalculator{ int value =0; public void add(Mineral mineral) { this.value += mineral.getvalue(); } public int getValue(){ return this.value; } } public class Sample { public static void main(String[] args) { MineralCalculator cal = new MineralCalculator(); cal.add(new Gold()); cal.add(new Silver()); cal.add(new Bronze()); System.out.println(cal.getValue()); } }
예제처럼 광물이 추가될때마다 add메소드를 추가하는것이 아니라 광물이 추가되더라도 MineralCalculator class를 수정할 필요없게 interface를 이용하여 구현해보았다. 일단 인터페이스를 만들어 getValue()추상메소드를 선언하고 gold silver bronze가 인터페이스를 implements하게 만든 후 각 각 다른 int형 숫자를 리턴하게끔 실체메소드를 작성해주었다. 그리고 MineralCalculator클래스의 add메소드의 매개변수로는 Mineral인터페이스 자료형으로 선언하였다. 이러면 Mineral인터페이스를 이용하는 모든 객체가 매개변수로 들어올 수 있어 새로운 광물이추가되더라도 MineralCalculator에 새로운 메소드를 추가할필요가없다. 인터페이스는 개발코드와 객체 사이에 중개하는역할을한다.
Q8
4번에서 오류발생 Dog클래스는 Animal클래스의 자식클래스로 IS-A관계가 성립될 수 없기 때문이다. 나머지는 모두 IS-A관계가성립
Q9
2번에서 오류발생 -> a객체가 Animal타입으로 생성되었기때문에 이런경우 부모 Animal의 메소드만 이용가능하다. 그러므로 자식 클래스 Lion에있는 bark메소드는 사용불가한것이다.
5번에서 오류발생 -> Predator타입 객체는 bark메소드만 사용가능한데, hello메소드를 호출하고있으므로 오류발생
만약 hello메소드도 호출하게 만들고 싶다면 Animal을 상속하면서 Predator를 인터페이스로 갖는 Lion클래스로 객체를 생성하면 hello메소드 호출가능하다.
'java' 카테고리의 다른 글
String.join (0) 2023.01.27 6장 연습문제 (0) 2023.01.27 4장 연습문제 (0) 2023.01.22 [java] 함수형 프로그래밍 (람다, 스트림) (0) 2023.01.20 [java] Thread / Runnable (0) 2023.01.20