30일차 - 2023.2.7

문우림·2023년 2월 7일
0

Java

목록 보기
14/23

1. 참조변수 간 대입과 형 변환

class Cake {
	public void sweet() {
		System.out.println("케익");
	}
}

class CheeseCake extends Cake {
	public void milky() {
		System.out.println("치즈 케익");
	}
}

public class CakeTest {

	public static void main(String[] args) {

		CheeseCake ca1 = new CheeseCake();
		Cake ca2 = ca1;
        ca2.sweet( );

		Cake ca3 = new Cake();
		CheeseCake ca4 = ca3; //에러

	}

}
[결과]
케익
  • ca3가 참조하는 대상을 컴파일러는 Cake인스턴스로 판단하여 에러남.
    (컴파일러는 문장 단위로 인식을 하기때문에 다음 문장으로 넘어가면 전 문장은 날아간다.)

찹조변수의 참조 가능성 : 배열 기반

2. 메소드(함수) 오버라이딩

2-1. 함수 오버라이딩이란...

상속 관계에서 함수를 만들 때 부모와 자식 함수의 데이터 타입, 이름, 파라미터는 다 똑같도, 바디만 달리 했을 때, 자식 함수가 부모 함수를 덮어쓰는 것.
함수 오버라이딩 = 함수 오버라이딩 자식꺼

2-2. 메소드 오버라이딩1

부모 클래스와 자식 클래스 안에 동일한 형태, 이름의 함수가 있을 때

class Cake {
	public void yummy() {
		System.out.println("Yummy Cake");
	}
}

class CheeseCake extends Cake {
	public void yummy() {
		System.out.println("Yummy Cheese Cake");
	}
}

public class Yummy {

	public static void main(String[] args) {
		Cake c1 = new CheeseCake();
		CheeseCake c2 = new CheeseCake();

		c1.yummy();
		c2.yummy();
	}

}

[결과]
Yummy Cheese Cake
Yummy Cheese Cake
  • CheeseCake(자식)의 Yummy메소드가 Cake(부모)의 Yummy메소드를 오버라이딩.

메소드 오버라이딩 조건

  • 부모와 자식의 상속 관계
  • 데이터 타입, 이름, 파라미터가 같은 함수 and 바디(내용)는 다르다.

2-3. 메소드 오버라이딩2

class Cake {
	public void yummy() {
		System.out.println("Yummy Cake");
	}
}

class CheeseCake extends Cake {
	public void yummy() {
		System.out.println("Yummy Cheese Cake"); // Cake의 yummy를 오버라이딩
	}
}

class StrawberryCheeseCake extends CheeseCake {
	public void yummy() {
		System.out.println("Yummy StrawberryCheeseCake "); // 그리고 CheeseCake의 yummy를 오버라이딩
	}
}

public class Yummy {

	public static void main(String[] args) {
		Cake c1 = new StrawberryCheeseCake();
		CheeseCake c2 = new StrawberryCheeseCake();
		StrawberryCheeseCake c3 = new StrawberryCheeseCake();

		c1.yummy();
		c2.yummy();
	}

}

[결과]
Yummy StrawberryCheeseCake 
Yummy StrawberryCheeseCake 

2-4. 오버라이딩 된 메소드 호출하는 방법(super사용)

  • 자식 함수 안에 super메소드를 사용하면 부모의 오버라이딩 된 함수를 호출할 수 있다.
    (부모로 부터 오버라이딩해서 받은 public void yummy( ){ }에 super.yummy( );를 넣는다)
class Cake {
	public void yummy() { //오버라이딩 된 메소드
		System.out.println("Yummy Cake");
	}
}

class CheeseCake extends Cake {
	public void yummy() {
		super.yummy();
		System.out.println("Yummy Cheese Cake"); // Cake의 yummy를 오버라이딩
	}

	public void tasty() {
		super.yummy();
		System.out.println("Yummy Tasty Cake");
	}
}

public class Yummy {

	public static void main(String[] args) {
		Cake c1 = new CheeseCake();
		CheeseCake c2 = new CheeseCake();

		c1.yummy();
		c2.tasty();

	}

}

[결과]
Yummy Cake
Yummy Cheese Cake
Yummy Cake
Yummy Tasty Cake

2-5. 오버로딩 / 오버라이딩 차이

오버로딩 : 같은 클래스 안에서 함수 이름은 같지만 데이터 타입, 파라미터 갯수가 다른 메소드르 를 여러개 선언하는 것.

오버라이딩 : 부모 와 자식 클래스의 상속 관계 이며 함수 이름, 파라미터, 반환형이 같은 메소드를 상속받은 클래스에서 내용을 덮어써서 사용할 수 있는 것.

3. 오버라이딩 예제 (도형의 넓이와 넓이의 합 구하기)

3-1. 따로따로 객체로만 만들었을 때

class Circle {
	private double rad;

	public Circle(double rad) {
		this.rad = rad;
	}

	public double getArea() {
		return (rad * rad) * Math.PI;
	}
}

class Rectangle {
	private double w, h;

	public Rectangle(double w, double h) {
		this.w = w;
		this.h = h;
	}

	public double getArea() {
		return (w * h);
	}
}

public class Overriding {

	public static void main(String[] args) {
		// 객체 생성
		Circle circle = new Circle(10);
		System.out.println(circle.getArea());

		Rectangle rec = new Rectangle(10, 20);
		System.out.println(rec.getArea());

		// circle.getArea() 의 rec.getArea() 합
		double areas = circle.getArea() + rec.getArea();
		System.out.println("총 면적의 합: " + areas);
	}

}


[결과]
314.1592653589793
200.0
총 면적의 합: 514.1592653589794

3-2. 상속 적용(배열, 오버라이딩 적용)

  • Shape 데이터 타입으로 Circle 객체, Rectangle 객체, Triangle 객체 만들기
  • Shape[]로 Circle, Rectangle, Triangle 초기화
  • for문을 이용해서 shape.getArea( ) 더하기
  • main( )과 같은 클래스 안에 static 적용한 함수 만들기
package com.fxmx.simple;

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

class Circle extends Shape {
	private double rad;

	public Circle(double rad) {
		this.rad = rad;
	}

	public double getArea() {
		return (rad * rad) * Math.PI;
	}
}

class Rectangle extends Shape {
	private double w, h;

	public Rectangle(double w, double h) {
		this.w = w;
		this.h = h;
	}

	public double getArea() {
		return (w * h);
	}
}

class Triangle extends Shape {
	private double w, h;

	public Triangle(double w, double h) {
		this.w = w;
		this.h = h;
	}

	public double getArea() {
		return (w * h) / 2.0;
	}

}

public class Overriding {

	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 Circle(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(main함수 결과)
총 면적의 합: 614.1592653589794(static함수 결과)

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

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 {
	public void print() {
		System.out.println("나는 포도이다.");
	}
}

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

class Pear extends Fruit {
	public void print() {
		System.out.println("나는 배이다.");
	}
}

public class FruitTest {

	public static void main(String[] args) {
		Fruit[] fAry = { new Grape(), new Apple(), new Pear() };
		for (Fruit f : fAry) {
			f.print();
		}
	}

}

2차원 배열에 랜덤으로 숫자를 넣어 출력하기.

4 X 4의 2차원 배열을 만들고 1부터 10까지범위 숫자를 랜덤으로 생성해서, 배열에 저장하기

public class DoubleArray {

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

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

	}

}

메인 밖에 static으로 배열 객체 생성

public class DoubleArray {
	private static int[][] twoArr = new int[4][4];
	
	public static void main(String[] args) {
	
		for(int i = 0; i < twoArr.length; i++) {
			for(int j = 0; j < twoArr[i].length; j++) {
				twoArr[i][j] = (int)(Math.random() * 10 + 1);
			}
		}
		for(int i = 0; i < twoArr.length; i++) {
			for(int j = 0; j < twoArr[i].length; j++) {
				System.out.print(twoArr[i][j] + "\t");
			}
			System.out.println();
		}
	}

}

0개의 댓글