본문 바로가기
Study/JAVA

[JAVA] 5주차_동적배열과 상속 (동적배열과 객체배열, 상속, Rectangle 클래스, OddEven 클래스)

by 8희 2022. 4. 3.

1차시 동적배열과 객체배열

 


동적 배열

- 크기를 미리 지정하는 배열은 정적 배열

- 처리할 데이터의 개수가 고정된 경우가 아니라면 정적 배열은 자원을 낭비하거나 프로그램을 다시 컴파일

- 자바는 크기가 유동적, 가변적, 동적인 배열을 지원하기 위해 ArrayList 클래스 제공

- 동적 배열은 배열이 요소에 따라 확장, 축소한다.

 

ArrayList 객체 생성

 

-> ArrayList<참조타입> 참조변수 = new ArrayList<>();

 

참조타입이 기초 타입이라면 Integer, Long, Short, Float, Double 등을 사용

 

ArrayList 원소 접근

 

참조변수.add(데이터)

참조변수. remove(인덱스번호)

참조변수.get(인덱스 번호)

참조변수.size()

 

/* ArrayList를 이용한 데이터의 평균 */

import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListDemo {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		ArrayList<Integer> scores = new ArrayList<>(); //Integer 타입의 ArrayList 생성
		int data;
		int sum = 0;

		while ((data = in.nextInt()) >= 0) //입력된 값이 음수일 시 while문 종료
			scores.add(data); //데이터를 동적 배열에 추가

//		for (int i = 0; i < scores.size(); i++)
//			sum += scores.get(i); //동적 배열의 i번째 원소를 가져옴

// 		for~each문 사용	
		for (int i : scores) // i == scores.size()
			sum += i; 		 // i는 scores(참조변수) 안에 있는 데이터의 크기

		System.out.println("평균 = " + sum / scores.size()); //동적배열의 크기
	}
}

객체 배열

: 객체 배열은 객체를 참조하는 주소를 원소로 구성

/* Ball 클래스의 객체로 구성된 배열을 선언하고 초기화 */

Ball[] balls = new Ball[5];

//5개의 Ball 객체를 생성하는 것이 아니라 5개의 Ball 객체를 참조할 변수를 준비한다.
//생성자를 호출하여 Ball 객체를 생성해야 한다.

/* Circle 객체의 배열과 출력 */

class Circle {
	double radius; //필드

	public Circle(double radius) { //생성자
		this.radius = radius;
	}

	public double getRadius() { //접근자
		return radius;
	}

	double findArea() { //원의 넓이 구하는 메서드
		return 3.14 * radius * radius;
	}
}

public class CircleArrayDemo {
	public static void main(String[] args) {
		Circle[] circles = new Circle[5];//객체 배열을 정의하고 선언

		for (int i = 0; i < circles.length; i++) { 
			circles[i] = new Circle(i + 1.0); //객체 배열의 공간 확보
			System.out.printf("원의 넓이(반지름 : %.1f) = %.2f\n", circles[i].radius, circles[i].findArea());
		}
	}
}

 

/* 객체 인수와 기초 타입 인수 */

public class ObjectArgumentDemo {
	public static void main(String[] args) {
		Circle c1 = new Circle(10.0);
		Circle c2 = new Circle(10.0);
        
        //메서드를 호출할 때 전달되는 값이 기본 자료형이면 값만 복사됨
		zero(c1); //참조변수 전달
		System.out.println("원(c1)의 반지름 : " + c1.radius);

		zero(c2.radius); 
		System.out.println("원(c2)의 반지름 : " + c2.radius);
	}
    
    //메서드 오버로딩
    //인수 타입이 매개변수 타입을 보고 실행할 메서드 결정
    
	public static void zero(Circle c) { //매개변수가 참조변수
		c.radius = 0.0;
	}

	public static void zero(double r) {
		r = 0.0;
	}
}

2차시 상속

 


상속: 자식 클래스에서 부모 클래스의 요소를 포함시켜서 구현하는 방법

 

상속의 필요성

: 공통된 필드와 메서드를 객체가 클래스를 만들 때마다 만들면 불편하다. 이러한 불편함을 해소하려면 상속을 이용해 코드를 재사용하면 된다.

 

 

상속과 클래스 멤버

부모 클래스 = 슈퍼 클래스 = 기본 클래스

자식 클래스 = 서브 클래스 = 파생 클래스

자식 클래스는 부모 클래스에서 물려받은 멤버를 그대로 사용하거나 변경할 수 있고, 새로운 멤버도 추가 가능

-> 자식 클래스는 대체로 부모 클래스보다 속성이나 동적이 더 많다.

 

상속의 선언

extends 키워드 사용하고, 다중 상속 X

/* 상속의 선언 예시 (코드 간결화) */

class SuperClass { //부모 클래스
	//필드
    //메서드
}

class SubClass extends SuperClass { //자식 클래스 선언 시 extends 키워드 사용해서 상속
	//필드
    //메서드
}


/* 다중 상속은 X */

//class SubClass extends SuperClass1, SuperClass2 {
} //이런 형식은 불가능하다.

 

/* Animal 클래스와 자식 클래스 */

public class Animal {
	String eye;
	String mouth;

	void eat() {
	}

	void sleep() {
	}
}

class Eagle extends Animal {
	String wing;

	void fly() {
	}
}

class Tiger extends Animal {
	String leg;

	void run() {
	}
}

class Goldfish extends Animal {
	String fin;

	void swim() {
	}
}

public class Circle {
	private void secret() { //private은 클래스 내부만 접근 허용
		System.out.println("비밀이다.");
	}

	protected void findRadius() { //protected는 부모, 자식 클래스만 접근 허용
		System.out.println("반지름이 10.0센티이다.");
	}

	public void findArea() { //public은 누구나 접근 가능
		System.out.println("넓이는 (π*반지름*반지름)이다.");
	}
}

public class Ball extends Circle { //Balldoth 사용할 수 있는 메서드는 총 5개
	private String color;

	public Ball(String color) {
		this.color = color;
	}

	public void findColor() {
		System.out.println(color + " 공이다.");
	}

	public void findVolume() {
		System.out.println("부피는 4/3*(π*반지름*반지름*반지름)이다.");
	}
}

public class InheritanceDemo {
	public static void main(String[] args) {
		Circle c1 = new Circle();
		Ball c2 = new Ball("빨간색");

		System.out.println("원 :");
		c1.findRadius(); //반지름은 10.0센티이다.
		c1.findArea(); //넓이는 (π*반지름*반지름)이다.

		System.out.println("\n공 :");
		c2.findRadius(); //반지름이 10.0센티이다.
		c2.findColor(); //빨간색 공이다.
		c2.findArea(); //넓이는 (π*반지름*반지름)이다.
		c2.findVolume(); //부피는 4/3*(π*반지름*반지름*반지름)이다.
	}
}

 


3차시 Rectangle 클래스, OddEven 클래스

 


사각형 면적 구하기 (Rectangle.java)

public class Rectangle {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
				
		System.out.print("가로 길이 : ");
		int width = in.nextInt();

		System.out.print("세로 길이 : ");  
		int height = in.nextInt();

		System.out.print("넓이 " + (double)width*height);
		
		isSame(width, height);
		in.close();
		}
	
	static void isSame(int width, int height) { //메인 메서드에서 접근해야 되니까 static
		System.out.println(width==height ? ", 정사각형" : ", 직사각형" );
	}

}

 

홀수짝수 구하기 (OddEven.java)

import java.util.Scanner;

public class OddEven {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);  
		
		while(true) {
			System.out.print("정수를 입력하세요 : ");  
			int num = in.nextInt();

			if (num < 0) {
				System.out.println("종료합니다.");
				break;
			}
			System.out.println( (num%2 == 0? "짝수" : "홀수") );
		}
	}

}