JAVA

클래스와 객체생성 및 활용

yujin0517 2021. 7. 5. 01:28

Ex 1) 사각형의 밑변 길이와 높이를 입력받아 둘레와 면적을 구하는 코드를 작성하기.

- 같은 클래스에 코드 작성하기. (Main 클래스)

import java.util.Scanner;

public class Main {
	int width, height;  //필드 선언
    
	public int getArea() {  //면적 구하기 메소드
		return width*height;
	}
    
	public int getCirc() {  //둘레 구하기 메소드 
		return 2*width*height;
	}
	public static void main(String[] args) {
    
		Scanner sc = new Scanner(System.in);  //객체 생성
		Main m = new Main();  //객체 생성
		
		m.width = sc.nextInt();  //객체 멤버 변수에 접근
		m.height = sc.nextInt();  //객체 멤버 변수에 접근
		
		System.out.println("사각형의 면적: " + m.getArea());
		System.out.println("사각형의 둘레: " + m.getCirc());
        
        sc.close();
	}
}

 

- 다른 클래스에 코드 작성하기. (Main 클래스, Rectangle 클래스)

public class Rectangle {
    int width, height;
    
    public int getArea() {
    	return width * height;
    }
    
    public int getCirc() {
    	return 2 * width * height;
    }
}
public class Main {
	public static void main(String[] args) {
    
    	Scanner sc = new String(System.in);
        Rectangle rect = new Rectangle();
        
        rect.width = sc.nextInt();
        rect.height = sc.nextInt();
        
        System.out.println("사각형의 면적: " + rect.getArea());
        System.out.println("사각형의 둘레: " + rect.getCirc());
        
        sc.close();
    }
}

 

콘솔창 출력 결과

 

Ex 2) 국영수 점수를 입력받아 평균값을 소수점 2 자리까지 출력되도록 하는 코드 작성하기.

public class Main {
	int kor, eng, mat;  //필드 선언

	public void readScore() {
		this.kor = 70;  //자기 자신의 객체에 값을 대입
		this.eng = 70;
		this.mat = 60;
	}

	public double scoreAvg() {  //평균 구하기 메소드
		return (kor + eng + mat) / 3.0;
	}

	public static void main(String[] args) {
		Main m = new Main();
		m.readScore();  //점수를 읽어오는 메소드에 접근
		System.out.printf("평균: %.2f", m.scoreAvg());
	}
}

콘솔창 출력 결과

 

Ex 3) 국가와 수도를 필드로 선언하여 지구라는 클래스를 선언하고, 생성자로 필드를 초기화하는 코드 작성하기.

public class Earth {  //Earth 클래스 선언
	String country, capital;  //필드 선언
    
	public Earth(String cap) {  //매개변수가 있는 생성자1
    	this.country = "한국";  // 자기 객체에 문자열 대입
        this.capital = cap;
    }
    
    public Earth(String coun, String cap) {  //매개변수가 있는 생성자2
    	this.country = coun;
        this.capital = cap;
    }
    public static void main(String[] args) {
    	Earth kor = new Earth("서울");  //매개변수가 하나만 입력되었으므로 생성자1과 연결
        Earth jap = new Earth("일본", "도쿄");  //매개변수가 하나만 입력되었으므로 생성자2와 연결
        
        System.out.println(kor.country + ", " + kor.capital);
        System.out.println(jap.country + ", " + jap.capital);
    }
}

콘솔창 출력 결과

 

다음 글에서는 접근지정자에 대해 설명하도록 하겠습니다.

감사합니다!

 

2021.07.04