본문 바로가기

Java

Java Advanced Programming Quiz

퀴즈 1: 제너릭 인터페이스 구현


문제: Transformer라는 제너릭 인터페이스를 정의하고, 이를 구현하는 StringToLengthTransformer 클래스를 작성하세요. Transformer 인터페이스는 하나의 메소드 T transform(F from)을 가집니다.
StringToLengthTransformer 클래스는 문자열을 받아 그 길이를 반환해야 합니다.

public interface Transformer<F, T> {
    T transform(F from);
}

public class StringToLengthTransformer implements Transformer<String, Integer> {
    @Override
    public Integer transform(String from) {
        return from.length();
    }
}

 

퀴즈 2: 다중 제한된 타입 매개변수

문제: printSumOfList라는 메소드를 작성하세요.
이 메소드는 List의 요소가 Number이면서 Comparable 인터페이스를 구현하는 제너릭 타입 T의 리스트를 매개변수로 받습니다.
리스트 내 모든 숫자의 합을 출력하세요.

public static <T extends Number & Comparable<T>> void printSumOfList(List<T> list) {
    double sum = 0;
    for (T element : list) {
        sum += element.doubleValue();
    }
    System.out.println("Sum: " + sum);
}

 

퀴즈 3: 제너릭 메소드와 와일드카드

문제: countGreaterThan라는 메소드를 작성하세요.
이 메소드는 제너릭 타입 T의 리스트와 T 타입의 요소를 매개변수로 받고, 주어진 요소보다 큰 리스트의 요소들의 개수를 반환합니다. T는 Comparable<T>를 상속받아야 합니다.

public static <T extends Comparable<T>> int countGreaterThan(List<T> list, T elem) {
    int count = 0;
    for (T element : list) {
        if (element.compareTo(elem) > 0) {
            count++;
        }
    }
    return count;
}

 

package com.intheeast.quiz1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
	
	public static <T extends Number & Comparable<T>> void printSumOfList(List<T> list) {
	    double sum = 0;
	    for (T element : list) {
	        sum += element.doubleValue();
	    }
	    System.out.println("Sum: " + sum);
	}
	
	public static <T extends Comparable<T>> int countGreaterThan(List<T> list, T elem) {
	    int count = 0;
	    for (T element : list) {
	        if (element.compareTo(elem) > 0) {
	            count++;
	        }
	    }
	    return count;
	}
	
	public static void testStringToLengthTransformerInstance() {
		StringToLengthTransformer transformer = new StringToLengthTransformer();

        String exampleString = "Hello, World!";

        Integer length = transformer.transform(exampleString);

        System.out.println("The length of '" + exampleString + "' is: " + length);
	}
	
	public static void testPrintSumOfList() {
		
		List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
		
		printSumOfList(integerList);
		
		List<Double> doubleList = Arrays.asList(1.5, 2.5, 3.5);
		
		printSumOfList(doubleList);
	}
	
	public static void testCountGreaterThan() {
		
		List<Integer> integerList2 = new ArrayList<>();
		integerList2.add(10);
		integerList2.add(5);
		integerList2.add(20);
		integerList2.add(8);
		integerList2.add(15);
		
		int greaterCount = countGreaterThan(integerList2, 12);
		
		System.out.println("특정 요소보다 큰 요소의 개수: " + greaterCount);
	}

	public static void main(String[] args) {
		
		testStringToLengthTransformerInstance();
		
		testPrintSumOfList();
		
		testCountGreaterThan();   
        
	}

}

퀴즈 4: 복잡한 제너릭 타입

문제: 다음은 Map과 List를 결합한 복잡한 제너릭 타입을 사용하는 예시입니다. 이 코드가 어떤 기능을 하는지 설명하세요.

Map<String, List<Integer>> map = new HashMap<>();
map.put("odd", Arrays.asList(1, 3, 5));
map.put("even", Arrays.asList(2, 4, 6));

for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

이 코드는 문자열 키와 정수 리스트를 값으로 가지는 맵을 생성하고, 이 맵에 "odd"와 "even"이라는 키에 각각 홀수와 짝수 리스트를 넣은 후, 맵의 모든 항목을 출력합니다.

퀴즈 5: 제너릭 클래스 상속

문제: NumberBox 클래스가 Box 클래스를 상속받도록 구현하세요. NumberBox는 숫자 타입만 받아야 하며, getDoubleValue 메소드를 통해 값을 double로 반환해야 합니다.

public class Box<T> {
    private T value;

    public Box(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }
}

public class NumberBox<T extends Number> extends Box<T> {
    // NumberBox 클래스 구현
}

 

public class NumberBox<T extends Number> extends Box<T> {
    public NumberBox(T value) {
        super(value);
    }

    public double getDoubleValue() {
        return getValue().doubleValue();
    }
}

퀴즈 6: 제너릭 타입 제한

문제: printMax라는 제너릭 메소드를 작성하세요. 이 메소드는 List의 요소가 Comparable 인터페이스를 구현하는 제너릭 타입 T의 리스트를 매개변수로 받습니다. 리스트에서 가장 큰 요소를 출력하세요.

public static <T extends Comparable<T>> void printMax(List<T> list) {
    if (list == null || list.isEmpty()) {
        System.out.println("List is empty");
        return;
    }

    T max = list.get(0);
    for (T element : list) {
        if (element.compareTo(max) > 0) {
            max = element;
        }
    }
    System.out.println("Max: " + max);
}

퀴즈 7: 제너릭 메소드와 컬렉션

문제: addAll이라는 이름의 제너릭 메소드를 만드세요. 이 메소드는 두 개의 Collection<T>을 매개변수로 받고, 첫 번째 컬렉션의 모든 요소를 두 번째 컬렉션에 추가합니다.

public static <T> void addAll(Collection<T> source, Collection<T> destination) {
    destination.addAll(source);
}



 

package com.intheeast.quiz2;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class Main {
	
	public static <T extends Comparable<T>> void printMax(List<T> list) {
	    if (list == null || list.isEmpty()) {
	        System.out.println("List is empty");
	        return;
	    }

	    T max = list.get(0);
	    for (T element : list) {
	        if (element.compareTo(max) > 0) {
	            max = element;
	        }
	    }
	    System.out.println("Max: " + max);
	}
	
	public static <T> void addAll(Collection<T> source, Collection<T> destination) {
	    destination.addAll(source);
	}
	
	public static void testNumberBoxInstance() {
		// Integer 타입의 NumberBox 객체 생성
        NumberBox<Integer> integerBox = new NumberBox<>(5);

        // Double 타입의 NumberBox 객체 생성
        NumberBox<Double> doubleBox = new NumberBox<>(10.5);

        // Float 타입의 NumberBox 객체 생성
        NumberBox<Float> floatBox = new NumberBox<>(7.3f);

        // getDoubleValue 메소드를 사용하여 double 값 얻기
        double intValueAsDouble = integerBox.getDoubleValue();
        double doubleValueAsDouble = doubleBox.getDoubleValue();
        double floatValueAsDouble = floatBox.getDoubleValue();

        // 결과 출력
        System.out.println("Integer 값의 double 형태: " + intValueAsDouble);
        System.out.println("Double 값의 double 형태: " + doubleValueAsDouble);
        System.out.println("Float 값의 double 형태: " + floatValueAsDouble);

	}
	
	public static void testAddAll() {
		// 첫 번째 리스트 생성
        List<Integer> sourceList = new ArrayList<>();
        sourceList.add(1);
        sourceList.add(2);
        sourceList.add(3);

        // 두 번째 리스트 생성
        List<Integer> destinationList = new ArrayList<>();
        destinationList.add(10);
        destinationList.add(20);

        // addAll 메소드를 사용하여 첫 번째 리스트의 모든 요소를 두 번째 리스트에 추가
        addAll(sourceList, destinationList);

        // 결과 출력
        System.out.println("Destination List after adding all elements from Source List: " + destinationList);
	}
	
	public static void testPrintMaxMethod() {
		// Integer 타입의 리스트 생성
        List<Integer> integerList = new ArrayList<>();
        integerList.add(10);
        integerList.add(5);
        integerList.add(20);
        integerList.add(8);
        integerList.add(15);

        // String 타입의 리스트 생성
        List<String> stringList = new ArrayList<>();
        stringList.add("apple");
        stringList.add("banana");
        stringList.add("orange");
        stringList.add("grape");

        // printMax 메소드를 사용하여 최대값 출력
        printMax(integerList);
        printMax(stringList);
	}
	
	

	public static void main(String[] args) {
		
	}

}

 

퀴즈 8: 제너릭 인터페이스 활용

문제: Function이라는 제너릭 인터페이스를 만들고, apply라는 메소드를 정의하세요. 이 메소드는 하나의 매개변수를 받고, 결과를 반환합니다. 그런 다음 UpperCaseFunction이라는 구현 클래스를 만들어, 문자열을 받아 대문자로 변환하는 기능을 구현하세요.

public interface Function<T, R> {
    R apply(T t);
}

public class UpperCaseFunction implements Function<String, String> {
    @Override
    public String apply(String s) {
        return s.toUpperCase();
    }
}

퀴즈 9: 제너릭 와일드카드 사용

문제: printNumberList라는 메소드를 만드세요. 이 메소드는 List<? extends Number> 타입의 리스트를 매개변수로 받고, 리스트의 모든 요소를 출력합니다.

public static void printNumberList(List<? extends Number> list) {
    for (Number n : list) {
        System.out.println(n);
    }
}

퀴즈 10: 제너릭과 예외 처리

문제: processElements라는 제너릭 메소드를 작성하세요. 이 메소드는 List<T> 타입의 리스트와 Processor<T> 타입의 객체를 매개변수로 받습니다. Processor<T> 인터페이스는 process라는 메소드를 가지며, 이 메소드는 예외를 던질 수 있습니다. processElements 메소드는 리스트의 각 요소에 process 메소드를 적용해야 합니다.

public interface Processor<T> {
    void process(T t) throws Exception;
}

public static <T> void processElements(List<T> list, Processor<T> processor) {
    for (T element : list) {
        try {
            processor.process(element);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

퀴즈 11: 제너릭 타입의 상속

문제: Shape라는 클래스를 만들고, Rectangle과 Circle이라는 두 하위 클래스를 정의하세요. 그런 다음 ShapeBox<T extends Shape>이라는 제너릭 클래스를 만들어, Shape 타입 또는 그 하위 타입의 인스턴스를 보관할 수 있도록 하세요.

public class Shape {}

public class Rectangle extends Shape {}

public class Circle extends Shape {}

public class ShapeBox<T extends Shape> {
    private T shape;

    public ShapeBox(T shape) {
        this.shape = shape;
    }

    public T getShape() {
        return shape;
    }
}

 

package com.intheeast.quiz3;

import java.util.ArrayList;
import java.util.List;

public class Main {
	
	public static void printNumberList(List<? extends Number> list) {
	    for (Number n : list) {
	        System.out.println(n);
	    }
	}
	
	public static <T> void processElements(List<T> list, Processor<T> processor) {
	    for (T element : list) {
	        try {
	            processor.process(element);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	}
	
	public static void testUpperCaseFunctionInstance() {
		// UpperCaseFunction 클래스의 객체 생성
        UpperCaseFunction upperCaseFunction = new UpperCaseFunction();

        // 문자열을 대문자로 변환하는 예제
        String inputString = "hello";
        String result = upperCaseFunction.apply(inputString);

        // 결과 출력
        System.out.println("Original String: " + inputString);
        System.out.println("String in Upper Case: " + result);
	}
	
	public static void testPrintNumberList() {
		// Integer 타입의 숫자 리스트 생성
        List<Integer> integerList = new ArrayList<>();
        integerList.add(10);
        integerList.add(20);
        integerList.add(30);

        // Double 타입의 숫자 리스트 생성
        List<Double> doubleList = new ArrayList<>();
        doubleList.add(10.5);
        doubleList.add(20.3);
        doubleList.add(30.8);

        // Float 타입의 숫자 리스트 생성
        List<Float> floatList = new ArrayList<>();
        floatList.add(5.5f);
        floatList.add(15.2f);
        floatList.add(25.7f);

        // printNumberList 메소드를 호출하여 각각의 숫자 리스트 출력
        printNumberList(integerList);
        printNumberList(doubleList);
        printNumberList(floatList);
	}
	
	public static void testProcessElementsMethod() {
		Processor<String> stringProcessor = new StringProcessor();

        // 정수를 처리하는 Processor 구현체 생성
        Processor<Integer> integerProcessor = new IntegerProcessor();

        // 문자열 리스트 생성
        List<String> stringList = new ArrayList<>();
        stringList.add("Hello");
        stringList.add("World");

        // 정수 리스트 생성
        List<Integer> integerList = new ArrayList<>();
        integerList.add(10);
        integerList.add(20);

        // processElements 메소드를 호출하여 각각의 리스트를 처리
        processElements(stringList, stringProcessor);
        processElements(integerList, integerProcessor);
	}
	
	public static void testShpeBoxInstance() {
		// ShapeBox 객체에 Shape을 담는 예제
        Shape shape = new Shape();
        ShapeBox<Shape> shapeBox1 = new ShapeBox<>(shape);

        // ShapeBox 객체에 Rectangle을 담는 예제
        Rectangle rectangle = new Rectangle();
        ShapeBox<Rectangle> shapeBox2 = new ShapeBox<>(rectangle);

        // ShapeBox 객체에 Circle을 담는 예제
        Circle circle = new Circle();
        ShapeBox<Circle> shapeBox3 = new ShapeBox<>(circle);

        // ShapeBox에서 객체를 가져와서 사용
        Shape retrievedShape1 = shapeBox1.getShape();
        Rectangle retrievedShape2 = shapeBox2.getShape();
        Circle retrievedShape3 = shapeBox3.getShape();

        // 결과 출력
        System.out.println("Retrieved Shape from shapeBox1: " + retrievedShape1);
        System.out.println("Retrieved Shape from shapeBox2: " + retrievedShape2);
        System.out.println("Retrieved Shape from shapeBox3: " + retrievedShape3);
	}


	public static void main(String[] args) {
//		testUpperCaseFunctionInstance();
//		testProcessElementsMethod();
		
		testShpeBoxInstance();
	}

}


//문자열을 처리하는 Processor 구현체
class StringProcessor implements Processor<String> {
	
	@Override
	public void process(String s) throws Exception {
	    System.out.println("Processing String: " + s);
	}
}

//정수를 처리하는 Processor 구현체
class IntegerProcessor implements Processor<Integer> {
	@Override
	public void process(Integer i) throws Exception {
		System.out.println("Processing Integer: " + i);
 }
}

 
 

퀴즈 12: 람다식 기본

문제: Runnable 인터페이스를 사용하는 람다식을 작성하여 쓰레드를 생성하고 실행하는 코드를 작성하세요.

Runnable task = () -> System.out.println("Running in a thread");
Thread thread = new Thread(task);
thread.start();

퀴즈 13: 함수형 인터페이스 사용

문제: Predicate<Integer> 함수형 인터페이스를 사용하여 주어진 정수 리스트에서 홀수만을 출력하는 코드를 작성하세요.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
Predicate<Integer> isOdd = n -> n % 2 != 0;
numbers.stream().filter(isOdd).forEach(System.out::println);

퀴즈 14: 람다식과 스트림

문제: 자바 스트림 API를 사용하여 문자열 리스트에서 길이가 4 이상인 문자열만을 필터링하고, 대문자로 변환하여 출력하는 코드를 작성하세요.

List<String> strings = Arrays.asList("Java", "Lambda", "Stream", "API");
strings.stream()
    .filter(s -> s.length() >= 4)
    .map(String::toUpperCase)
    .forEach(System.out::println);

퀴즈 15: 람다식과 메소드 참조

문제: Consumer<String> 함수형 인터페이스를 사용하는 람다식과 메소드 참조를 사용하여 문자열 리스트의 각 요소를 출력하는 두 가지 방법의 코드를 작성하세요.
※String 의 forEach를 활용하세요

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}
List<String> strings = Arrays.asList("Java", "Lambda", "Stream");
strings.forEach(s -> System.out.println(s));
strings.forEach(System.out::println);



 

package com.intheeast.quiz4;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Main {
	
	public static void testLambdaExpression() {
		Runnable task = () -> System.out.println("Running in a thread");
		Thread thread = new Thread(task);
		thread.start();		
	}
	
	public static void testFunctionalInterface() {
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
		Predicate<Integer> isOdd = n -> n % 2 != 0;
		numbers.stream().filter(isOdd).forEach(System.out::println);
	}

	public static void testLambdaStream() {
		List<String> strings = Arrays.asList("Java", "Lambda", "Stream", "API");
		strings.stream()
		    .filter(s -> s.length() >= 4)
		    .map(String::toUpperCase)
		    .forEach(System.out::println);

	}

	public static void testMethodReference() {
		List<String> strings = Arrays.asList("Java", "Lambda", "Stream");
		
		// 람다식
		strings.forEach(s -> System.out.println(s));
		
		// 메소드 레퍼런스
		strings.forEach(System.out::println);

	}
	
	public static void main(String[] args) {
		testLambdaExpression();
		testFunctionalInterface();
		testLambdaStream();
		testMethodReference();
	}

}

 

퀴즈 16: 람다식과 컬렉션

문제: List<String>에서 각 문자열의 길이를 기준으로 정렬하는 코드를 람다식을 사용하여 작성하세요.

List<String> list = Arrays.asList("Lambda", "Stream", "Java");
list.sort((s1, s2) -> s1.length() - s2.length());
list.forEach(System.out::println);

퀴즈 17: 람다식과 Comparator

문제: Comparator 인터페이스를 사용하여 두 Integer 객체를 비교하는 람다식을 작성하세요. 이 람다식은 더 큰 수를 반환해야 합니다.

Comparator<Integer> comparator = (a, b) -> a > b ? a : b;
System.out.println(comparator.compare(3, 5));

퀴즈 18: 함수형 인터페이스와 람다식

문제: Function<String, Integer> 함수형 인터페이스를 사용하여 문자열의 길이를 반환하는 람다식을 작성하세요.

Function<String, Integer> lengthFunction = s -> s.length();
System.out.println(lengthFunction.apply("Lambda"));

퀴즈 19: 람다식과 스트림 API

문제: 자바 스트림 API를 사용하여 정수 리스트에서 짝수만을 필터링하고, 각 숫자의 제곱을 출력하는 코드를 람다식을 사용하여 작성하세요.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
    .filter(n -> n % 2 == 0)
    .map(n -> n * n)
    .forEach(System.out::println);



package com.intheeast.quiz5;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

public class Main {
	
	public static void testLambdaCollection() {
		List<String> list = Arrays.asList("Lambda", "Stream", "Java");
		list.sort((s1, s2) -> s1.length() - s2.length());
		list.forEach(System.out::println);
	}
	
	public static void testLambdaComparator() {
		Comparator<Integer> comparator = (a, b) -> a > b ? a : b;
		System.out.println(comparator.compare(3, 5));
	}
	
	public static void testFunctionalInterfaceLambda() {
		Function<String, Integer> lengthFunction = s -> s.length();
		System.out.println(lengthFunction.apply("Lambda"));
	}
	
	public static void testLambdaStream() {
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
		numbers.stream()
		    .filter(n -> n % 2 == 0)
		    .map(n -> n * n)
		    .forEach(System.out::println);
	}

	public static void main(String[] args) {
		testLambdaCollection();
		testLambdaComparator();
		testFunctionalInterfaceLambda();
		testLambdaStream();
	}

}

 

퀴즈 20: 추상 클래스와 인터페이스

문제: Shape라는 추상 클래스와 Drawable이라는 인터페이스를 만들고, Circle이라는 클래스가 이 둘을 구현하도록 작성하세요. Shape 클래스는 area() 메소드를 갖고, Drawable 인터페이스는 draw() 메소드를 갖습니다.

abstract class Shape {
    abstract double area();
}

interface Drawable {
    void draw();
}

class Circle extends Shape implements Drawable {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * radius * radius;
    }

    @Override
    public void draw() {
        System.out.println("Drawing Circle");
    }
}

퀴즈 21: 제너릭과 중첩 클래스

문제: 제너릭 클래스 Container<T> 내부에 Pair<K, V>라는 정적 중첩 클래스를 정의하세요. Container 클래스는 Pair 객체를 저장하며, getPair() 메소드를 통해 이를 반환합니다.

public class Container<T> {
    private T value;

    public Container(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }
    
    public void setValue(T value) {
    	this.value = value;
    }

    public static class Pair<K, V> {
        private K key;
        private V value;

        public Pair(K key, V value) {
            this.key = key;
            this.value = value;
        }

        public K getKey() {
            return key;
        }

        public V getValue() {
            return value;
        }
    }
    
    public <K, V> Pair<K, V> getPair(K key, V value) {
        return new Pair<>(key, value);
    }
}

퀴즈 22: 람다식과 함수형 인터페이스

문제: Processor라는 함수형 인터페이스를 정의하고, 이를 사용하는 processData 메소드를 작성하세요. Processor 인터페이스는 String 타입을 입력받아 String 타입을 반환하는 process 메소드를 가집니다. processData 메소드는 String과 Processor를 매개변수로 받아, 처리 결과를 출력합니다.

@FunctionalInterface
interface Processor {
    String process(String input);
}

public class Main {
    public static void processData(String data, Processor processor) {
        System.out.println(processor.process(data));
    }

    public static void main(String[] args) {
        processData("Hello", str -> str.toUpperCase());
    }
}

퀴즈 23: 람다식과 스트림 API

문제: List<Integer>에서 각 숫자의 제곱을 구하고, 이 중 홀수인 것만을 필터링하여 합계를 구하는 람다식과 스트림을 사용한 코드를 작성하세요.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
                .map(n -> n * n)
                .filter(n -> n % 2 != 0)
                .reduce(0, Integer::sum);
System.out.println("Sum of odd squares: " + sum);

 
 

package com.intheeast.quiz6;

import java.util.Arrays;
import java.util.List;

public class Main {
	
	public static void testCircleInstance() {
		// Circle 클래스의 객체 생성
        Circle circle = new Circle(5.0);

        // Circle 클래스의 area 메소드를 사용하여 원의 면적 계산 및 출력
        double circleArea = circle.area();
        System.out.println("Circle Area: " + circleArea);

        // Circle 클래스의 draw 메소드를 사용하여 도형 그리기
        circle.draw();
	}
	
	public static void testContainerInstance() {
		// Creating a Container with Integer value
        Container<Integer> intContainer = new Container<>(42);
        int intValue = intContainer.getValue();
        System.out.println("Container with Integer value: " + intValue);

        // Creating a Container with String value
        Container<String> stringContainer = new Container<>("Hello, Generics!");
        String stringValue = stringContainer.getValue();
        System.out.println("Container with String value: " + stringValue);

        // Creating a Pair using the getPair method
        Container.Pair<Integer, Double> pair = stringContainer.getPair(1, 3.14);
        int key = pair.getKey();
        double value = pair.getValue();
        System.out.println("Pair key: " + key + ", Pair value: " + value);
    }
	
	public static void testProcessorInterface(String data, Processor processor) {
        System.out.println(processor.process(data));
    }
	
	public static void testLambdaStream() {
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
		int sum = numbers.stream()
		                .map(n -> n * n)
		                .filter(n -> n % 2 != 0)
		                .reduce(0, Integer::sum);
		System.out.println("Sum of odd squares: " + sum);
	}
	
	public static void main(String[] args) {
		testCircleInstance();
		testContainerInstance();
		testProcessorInterface("Hello", str -> str.toUpperCase());
		testLambdaStream();
    }

}

 

퀴즈 24: 복합 인터페이스와 추상 클래스

문제: Animal이라는 추상 클래스와 Movable 및 Eatable이라는 두 인터페이스를 정의하세요. 그런 다음, Dog 클래스가 이들을 모두 구현하도록 작성하세요. 각 클래스와 인터페이스는 적어도 하나의 메소드를 가져야 합니다.

abstract class Animal {
    abstract void eat();
}

interface Movable {
    void move();
}

interface Eatable {
    void beEaten();
}

class Dog extends Animal implements Movable, Eatable {
    @Override
    void eat() {
        System.out.println("Dog eats");
    }

    @Override
    public void move() {
        System.out.println("Dog moves");
    }

    @Override
    public void beEaten() {
        System.out.println("Dog can be eaten");
    }
}

퀴즈 25: 제너릭 클래스와 중첩 클래스

문제: House<T>라는 제너릭 클래스를 만들고, 이 클래스 내부에 Room이라는 정적 중첩 클래스를 정의하세요. House 클래스는 Room 객체의 리스트를 유지하며, addRoom과 getRooms 메소드를 포함해야 합니다.

public class House<T> {
    private List<Room> rooms = new ArrayList<>();

    public static class Room {
        // Room 클래스 구현
    }

    public void addRoom(Room room) {
        rooms.add(room);
    }

    public List<Room> getRooms() {
        return rooms;
    }
}

퀴즈 26: 람다식과 함수형 인터페이스

문제: Calculator라는 함수형 인터페이스를 정의하고, 이 인터페이스를 사용하여 두 숫자의 합, 차, 곱, 나눗셈을 수행하는 람다식을 작성하세요.

@FunctionalInterface
interface Calculator {
    double calculate(double a, double b);
}

public class Main {
    public static void main(String[] args) {
        Calculator add = (a, b) -> a + b;
        Calculator subtract = (a, b) -> a - b;
        Calculator multiply = (a, b) -> a * b;
        Calculator divide = (a, b) -> a / b;
    }
}

퀴즈 27: 인터페이스의 디폴트 메소드

문제: Greetable이라는 인터페이스를 작성하고, hello와 goodbye라는 두 개의 디폴트 메소드를 정의하세요. 그런 다음, 이 인터페이스를 구현하는 Person 클래스를 작성하세요.

interface Greetable {
    default void hello() {
        System.out.println("Hello");
    }

    default void goodbye() {
        System.out.println("Goodbye");
    }
}

class Person implements Greetable {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public void introduce() {
        System.out.println("My name is " + name + ".");
    }
}

 

package com.intheeast.quiz7;

import java.util.List;

public class Main {
	
	public static void testHouse() {
        // Creating a House with Integer type
        House<Integer> house1 = new House<>();
        House.Room room1 = new House.Room();
        house1.addRoom(room1);

        // Creating a House with String type
        House<String> house2 = new House<>();
        House.Room room2 = new House.Room();
        house2.addRoom(room2);

        // Getting rooms from each house
        List<House.Room> rooms1 = house1.getRooms();
        List<House.Room> rooms2 = house2.getRooms();

        // Outputting information
        System.out.println("House 1 rooms count: " + rooms1.size());
        System.out.println("House 2 rooms count: " + rooms2.size());
    }
	
	public static void testCalculator() {
		Calculator add = (a, b) -> a + b;
        Calculator subtract = (a, b) -> a - b;
        Calculator multiply = (a, b) -> a * b;
        Calculator divide = (a, b) -> a / b;
        
        System.out.println("add: " +add.calculate(10, 20));
        System.out.println("subtract: " +subtract.calculate(100, 20));
        System.out.println("multiply: " +multiply.calculate(10, 20));
        System.out.println("divide: " +divide.calculate(100, 20));
	}
	
	public static void testPerson() {
        Person person = new Person("John");
        person.introduce();  // "My name is John."
        person.hello();      // "Hello"
        person.goodbye();    // "Goodbye"
    }

	public static void main(String[] args) {
		testHouse();
		testCalculator();
		testPerson();

	}

}

퀴즈: 종합적인 자바 도전과제

문제: Garden이라는 클래스를 만들어야 합니다. 이 클래스는 다음과 같은 요구 사항을 충족해야 합니다:

  1. 추상 클래스 & 인터페이스:
    • Garden은 추상 메소드 describeGarden()을 포함하는 추상 클래스여야 합니다.
    • grow()라는 추상 메소드를 가진 Growable 인터페이스를 정의하고, Garden이 이 인터페이스를 구현하도록 합니다.
  2. 제너릭 클래스:
    • Garden 클래스 내부에 다양한 종류의 식물에 대한 정보를 보유할 수 있는 제너릭 Plant 클래스를 만듭니다.
  3. 중첩 클래스:
    • Plant 내에 정적 중첩 클래스 Fruit와 비정적 내부 클래스 Flower를 생성합니다.
    • Fruit은 printFruitType() 메소드를, Flower는 printFlowerColor() 메소드를 가져야 합니다.
  4. 람다 표현식:
    • main 메소드에서 람다 표현식을 사용하여 Growable의 인스턴스를 생성하고 grow() 메소드를 호출합니다.
  5. 함수형 인터페이스:
    • 함수형 인터페이스와 람다 표현식을 사용하여 Garden 내의 Plant 객체에 대한 정보를 출력하는 displayPlant 메소드를 만듭니다.

Garden 클래스, 그 내부 클래스들 및 main 메소드의 샘플 구현을 제공하여 이러한 개념들의 사용 방법을 보여주세요.
 

public interface Growable {
	void grow();
}

 

public abstract class Garden implements Growable {
    abstract void describeGarden();

    @Override
    public void grow() {
        System.out.println("Garden is growing!");
    }

    static class Plant<T> {
        T plantDetail;

        static class Fruit {
            void printFruitType() {
                System.out.println("Fruit type");
            }
        }

        class Flower {
            void printFlowerColor() {
                System.out.println("Flower color");
            }
        }
    }
}

 

import java.util.function.Function;

public class Main {
	
	public static <T> void displayPlant(Garden.Plant<T> plant, Function<Garden.Plant<T>, String> func) {
        System.out.println(func.apply(plant));
    }
	
    public static void main(String[] args) {
        Garden garden = new Garden() {
            @Override
            void describeGarden() {
                System.out.println("Beautiful Garden");
            }
        };

        garden.grow();

        Garden.Plant<String> plant = new Garden.Plant<>();
        Garden.Plant.Fruit apple = new Garden.Plant.Fruit();
        Garden.Plant<String>.Flower rose = plant.new Flower();

        apple.printFruitType();
        rose.printFlowerColor();

        // 람다식을 사용한 함수형 인터페이스 구현
        Growable growable = () -> System.out.println("Growing using lambda!");
        growable.grow();

        // displayPlant 메소드 구현
        displayPlant(plant, p -> "Plant detail: " + p.plantDetail);
    }

    
}

 
 

퀴즈: 고급 자바 프로그래밍 도전

문제: 다음 요구 사항에 맞는 자바 프로그램을 작성하세요:

  1. 인터페이스 & 추상 클래스:
    • Flying이라는 인터페이스를 만들고, fly()라는 추상 메소드를 정의하세요.
    • Bird라는 추상 클래스를 만들고, sing()이라는 추상 메소드를 정의하세요. Bird 클래스는 Flying 인터페이스를 구현해야 합니다.
  2. 제너릭 클래스:
    • Cage<T extends Bird>라는 제너릭 클래스를 만듭니다. 이 클래스는 Bird의 서브클래스만 받아야 합니다.
  3. 내부 클래스:
    • Bird 클래스 내에 Wing이라는 내부 클래스를 만들고, flap() 메소드를 정의하세요.
  4. 람다식:
    • Flying 인터페이스를 람다식으로 구현하여 인스턴스를 생성하고, fly() 메소드를 호출하는 코드를 작성하세요.
public interface Flying {
    void fly();
}
package com.intheeast.quiz9;

public abstract class Bird implements Flying {
    abstract void sing();

    // 내부 클래스 정의
    class Wing {
        void flap() {
            System.out.println("Wing flaps");
        }
    }
}
package com.intheeast.quiz9;

public class Cage<T extends Bird> {
    private T bird;

    public Cage(T bird) {
        this.bird = bird;
    }

    public T getBird() {
        return bird;
    }
}

 

package com.intheeast.quiz9;

public class Main {

	public static void main(String[] args) {
		
        // 람다식을 이용한 Flying 인터페이스 구현
        Flying flyingBird = () -> System.out.println("Bird is flying");
        flyingBird.fly();

        // Bird의 서브클래스 인스턴스와 Cage 인스턴스 생성
        Bird myBird = new Bird() {
            @Override
            void sing() {
                System.out.println("Bird sings");
            }

            @Override
            public void fly() {
                System.out.println("Bird flies");
            }
        };
        Cage<Bird> birdCage = new Cage<>(myBird);

        // 내부 클래스와 추상 메소드 사용
        myBird.sing();
        myBird.new Wing().flap();
    }

}

 

퀴즈: 종합적인 자바 코딩 도전 2

문제: 다음 조건을 만족하는 자바 프로그램을 작성하세요:

  1. 추상 클래스 & 인터페이스:
    • Vehicle이라는 추상 클래스를 만들고, drive()라는 추상 메소드를 정의하세요.
    • Refuelable이라는 인터페이스를 만들고, refuel()이라는 메소드를 정의하세요. Car 클래스는 Vehicle을 상속받고 Refuelable을 구현해야 합니다.
  2. 제너릭 클래스:
    • Garage<T extends Vehicle>이라는 제너릭 클래스를 만들고, Vehicle의 서브클래스만 보관할 수 있어야 합니다.
  3. 중첩 클래스:
    • Car 클래스 내에 Engine이라는 내부 클래스를 만들고, start() 메소드를 정의하세요.
  4. 람다식:
    • Refuelable 인터페이스의 인스턴스를 람다식으로 생성하고, refuel() 메소드를 호출하는 코드를 작성하세요.

 

 
// 추상 클래스 정의
abstract class Vehicle {
    abstract void drive();
}

// 인터페이스 정의
interface Refuelable {
    void refuel();
}

// Car 클래스
class Car extends Vehicle implements Refuelable {
    // 내부 클래스 정의
    class Engine {
        void start() {
            System.out.println("Engine starts");
        }
    }

    @Override
    void drive() {
        System.out.println("Car drives");
    }

    @Override
    public void refuel() {
        System.out.println("Car refuels");
    }
}

// 제너릭 클래스 정의
class Garage<T extends Vehicle> {
    private T vehicle;

    public Garage(T vehicle) {
        this.vehicle = vehicle;
    }

    public T getVehicle() {
        return vehicle;
    }
}

// 메인 클래스
public class Main {
    public static void main(String[] args) {
        // 람다식을 이용한 Refuelable 인터페이스 구현
        Refuelable refuelable = () -> System.out.println("Refueling vehicle");
        refuelable.refuel();

        // Car 인스턴스와 Garage 인스턴스 생성
        Car myCar = new Car();
        Garage<Car> myGarage = new Garage<>(myCar);

        // Car의 메소드와 Engine 내부 클래스 사용
        myCar.drive();
        myCar.new Engine().start();
    }
}

 

퀴즈: 종합적인 자바 코딩 도전 3

문제: 다음 요구 사항에 맞게 자바 프로그램을 작성하세요:

  1. 추상 클래스와 인터페이스:
    • Animal이라는 추상 클래스를 만들고, eat()라는 추상 메소드를 정의하세요.
    • NoiseMaker라는 인터페이스를 만들고, makeNoise()라는 메소드를 정의하세요. Dog 클래스는 Animal을 상속받고 NoiseMaker를 구현해야 합니다.
  2. 제너릭 클래스:
    • Shelter<T extends Animal>이라는 제너릭 클래스를 만들고, Animal의 서브클래스만 보관할 수 있어야 합니다.
  3. 중첩 클래스:
    • Dog 클래스 내에 Breed라는 열거형을 정의하고, 몇 가지 개의 품종을 나열하세요.
  4. 람다식:
    • NoiseMaker 인터페이스의 인스턴스를 람다식으로 생성하고, makeNoise() 메소드를 호출하는 코드를 작성하세요.
// 추상 클래스 정의
abstract class Animal {
    abstract void eat();
}

// 인터페이스 정의
interface NoiseMaker {
    void makeNoise();
}

// Dog 클래스
class Dog extends Animal implements NoiseMaker {
    // 중첩 열거형 정의
    enum Breed {
        LABRADOR, BULLDOG, BEAGLE
    }

    @Override
    void eat() {
        System.out.println("Dog eats");
    }

    @Override
    public void makeNoise() {
        System.out.println("Dog barks");
    }
}

// 제너릭 클래스 정의
class Shelter<T extends Animal> {
    private T animal;

    public Shelter(T animal) {
        this.animal = animal;
    }

    public T getAnimal() {
        return animal;
    }
}

// 메인 클래스
public class Main {
    public static void main(String[] args) {
        // 람다식을 이용한 NoiseMaker 인터페이스 구현
        NoiseMaker noiseMaker = () -> System.out.println("Generic animal noise");
        noiseMaker.makeNoise();

        // Dog 인스턴스와 Shelter 인스턴스 생성
        Dog myDog = new Dog();
        Shelter<Dog> dogShelter = new Shelter<>(myDog);

        // Dog의 메소드 사용
        myDog.eat();
        myDog.makeNoise();
    }
}

'Java' 카테고리의 다른 글

Java Collection Framework  (0) 2024.04.08
Lambda Expressions  (0) 2024.04.08
Scope  (0) 2024.04.08
Package  (0) 2024.04.08
Concurrency 1  (0) 2024.04.08