2023-02-07 화 / JAVA

권혁현·2023년 2월 7일
0

Java

목록 보기
28/44
post-thumbnail

1. 메소드 오버라이딩(Overriding) 이란?

  • 상속 관계에서 함수를 만들 때 부모,자식 함수에서 바디만 달리 했을 때 자식의 함수가 부모의 함수를 덮어쓴다 = 함수 오버라이딩 = 자식꺼

2. 오버로딩 vs 오버라이딩 에 대하여 설명하시오.

  • 오버로딩
    같은 클래스 안에 존재하는 함수명은 같지만 파라미터가 서로 다른 함수

  • 오버라이딩
    상속 관계에서 함수를 만들 때 부모,자식 함수에서 바디만 달리 했을 때 자식의 함수가 부모의 함수를 덮어쓴다

3. 아래를 프로그래밍 하시오.

    Fruit fAry[] = {new Grape(), new Apple(), new Pear());
   	for(Fruit f : fAry) {
   	    f.print();
   	}
  • 결과
    나는 포도이다.
    나는 사과이다.
    나는 배이다.

class Fruit{
	public void print() {
		System.out.println("나는 과일이다");
	}
}

class Grape extends Fruit{
	
	@Override
	public void print() {
		System.out.println("나는 포도이다");
	}
}
class Apple extends Fruit{
	
	@Override
	public void print() {
		System.out.println("나는 사과이다");
	}
}
class Pear extends Fruit{
	
	@Override
	public void print() {
		System.out.println("나는 배이다");
	}
}

4. 아래를 main 함수에 넣고 돌아 가도록 하시오.

    Shape[] shapeArr = {
   		new Circle2(10), new Rectangle(10,20),new Triangle(10,20)    			
    };
    	
    double sum = 0;
    for (Shape shape : shapeArr) {
		sum += shape.getArea();
	}
    System.out.println("총 면적은:" + sum);
    	
    	
    shapeAllArea(shapeArr); //총 면적은:614.1592653589794

class Shape {
	public double getArea() {
		return 0;
	}

}

class Circle15 extends Shape {
	private double radius;

	public Circle15(double radius) {
		this.radius = radius;
	}

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

class Rectangle15 extends Shape {
	private double whidth, height;

	public Rectangle15(double whidth, double height) {
		this.whidth = whidth;
		this.height = height;
	}

	@Override
	public double getArea() {
		return whidth * height;
	}
}

class Triangle15 extends Shape {
	private double whidth, height;

	public Triangle15(double whidth, double height) {
		this.whidth = whidth;
		this.height = height;
	}

	@Override
	public double getArea() {
		return whidth * height / 2;
	}

}
public class Study20 {

	static void shapeAllArea(Shape[] shapeArr) {
		double sum = 0;
		for (Shape shape : shapeArr) {
			sum += shape.getArea();
		}
		System.out.println("총 면적의 합 : " + sum);
	}

	public static void main(String[] args) {
    	Shape[] shapeArr = { 
        	new Circle15(10), new Rectangle15(10, 20), new Triangle15(10, 20)
        };

		double sum = 0;
		for (Shape shape : shapeArr) {
			sum += shape.getArea();
		}
		System.out.println("총 면적의 합 : " + sum);

		shapeAllArea(shapeArr); // 총 면적의 합 : 614.1592653589794

4.아래의 프로그램을 짜시오. (필수)

4 x 4의 2차원 배열을 만들고 이곳에 1에서 10까지 범위의 정수를
랜덤하게 생성하여 정수 16개를 배열에 저장하고, 2차원 배열을 화면에 출력하라.

8 6 1 1
7 3 6 9
4 5 3 7
9 6 3 1


public static void main(String[] args) {
		int[][] arr = new int[4][4];

		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr[i].length; j++) {
				arr[i][j] = (int) ((Math.random() * 9) + 1);
				System.out.print(arr[i][j] + " ");
			}
			System.out.println();
		}
	}

0개의 댓글