Part14 - access_modifier

uglyduck.dev·2020년 9월 27일
0

예제로 알아보기 👀

목록 보기
14/22
post-thumbnail

Book

package com.mywork.ex;

public class Book {
	// Field
	private String title;
	private String writer;
	private int price;
	private int salesVolume;        // 판매량
	private boolean isBestSeller;   // 판매량이 1000 이상이면 true, 아니면 false
	
	// Constructor
	public Book() {}
	public Book(String title, String writer, int price) {
		this.title = title;
		this.writer = writer;
		this.price = price;
	}
	public Book(String title, int price) {
		this(title, "작자미상", price);
	}
	
	// Method
	
	public void setTitle(String title) {
		this.title = title;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public void setSalesVolume(int salesVolume) {
		this.salesVolume = salesVolume;
		setBestSeller((salesVolume >= 1000) ? true : false);
	}
	public void setBestSeller(boolean isBestSeller) {
		this.isBestSeller = isBestSeller;
	}
	
	public String getTitle() {
		return title;
	}
	public String getWriter() {
		return writer;
	}
	public int getPrice() {
		return price;
	}
	public int getSalesVolume() {
		return salesVolume;
	}
	public boolean isBestSeller() {
		return isBestSeller;
	}
	
	public void output() {
		System.out.println("제목 : " + title);
		System.out.println("저자 : " + writer);
		System.out.println("가격 : " + price);
		System.out.println("판매량 : " + salesVolume);
		System.out.println(isBestSeller ? "베스트셀러" : "일반서적");
	}

}

BookMain

package com.mywork.ex;

public class BookMain {

	public static void main(String[] args) {
		Book book1 = new Book();
		Book book2 = new Book("콩쥐팥쥐", 10000);
		Book book3 = new Book("도전 자바 200문제", "김자바" ,25000);
		
		book1.setSalesVolume(0);
		book2.setSalesVolume(500);
		book3.setSalesVolume(1500);
		
		book1.output();		System.out.println("-----");
		book2.output();		System.out.println("-----");
		book3.output();
	}

}

Circle

package com.mywork.ex;

public class Circle {

	// Field              // 필드는 public 처리하지 않는다.(권장)
	private int x;
	private int y;
	private double radius;
	
	// Constructor        // Constructor에도 private 처리가 가능 -> 나만 생성할 수 있다
	public Circle() {     // 외부에서 사용 못하게.
		this(0, 0, 1);
	}
	public Circle(double radius) {
		this(0, 0, radius);
	}
	public Circle(int x, int y, double radius) {
		this.x = x;
		this.y = y;
		this.radius = radius;
	}
	
	// Method
	private double calcArea() {           	// 외부에 공개하고 싶지 않은 공식이 들어간 경우 public처리 하지 않는다.
		return radius * radius * Math.PI; // private 처리한다. -> output() 함수에만 사용되므로 private처리 가능
	}
	private double calcCircum() {
		return 2 * Math.PI * radius;
	}
	public void output() {
		System.out.println("중심좌표 : [" + x + ", " + y + "]");
		System.out.println("반지름 : " + radius);
		System.out.println("크기 : " + calcArea());
		System.out.println("둘레 : " + calcCircum());		
	}
	
}

CircleMain

package com.mywork.ex;

public class CircleMain {

	public static void main(String[] args) {
		Circle circle1 = new Circle();
		Circle circle2 = new Circle(1.5);
		Circle circle3 = new Circle(3, 3, 2.5);
		
		circle1.output();
		circle2.output();
		circle3.output();
	}

}

Local

package com.mywork.ex;

public class Local {

	// Field
	private String name;
	private int age;
	private String sn;           // 주민등록번호(식별번호가 1~4는 한국인, 5~8은 외국인, 주민등록번호가 없어도 외국인)
	private boolean isKorean;    // 한국인: true, 외국인: false
	
	// Constructor
	public Local() {}
	public Local(String name, int age) {
		this(name, age, null);
	}
	public Local(String name, int age, String sn) {
		this.name = name;
		this.age = age;
		this.sn = sn;
		if(sn != null) {
			this.isKorean = sn.charAt(7) <= '4' ? true : false;
		}else{
			this.isKorean = false;
		}
	}
	// Method
	public void output() {
		System.out.println("이름 : " + name);
		System.out.println("나이 : " + age);
		System.out.println("주민등록번호 : " + (sn == null ? "없음" : sn));
		System.out.println(isKorean ? "한국인" : "외국인");
	}
	
}

LocalMain

package com.mywork.ex;

public class LocalMain {

	public static void main(String[] args) {

		Local person1 = new Local("홍길동", 20, "901215-1234567");
		Local person2 = new Local("응우엔티엔", 21, "911215-6789123");
		Local person3 = new Local("james", 22);
		
		person1.output();	System.out.println("-----");
		person2.output();	System.out.println("-----");
		person3.output();
		
	}

}

Person

package com.mywork.ex;

public class Person {
	
        // Field (default 접근 지시자인 경우)
        // String name;
        // int age;
        // double height;
        // char gender;
		
	// Field
	private String name;
	private int age;
	private double height;
	private char gender;
	private boolean isKorean;
	
	// Constructor
	public Person() {}
	public Person(String name, int age, double height, char gender) {
		this.name = name;
		this.age = age;
		this.height = height;
		this.gender = gender;
		this.isKorean = true;
	}
	
	// Method
	public void setName(String name) {
		// 이름의 길이는 반드시 2 이상이어야 한다.
		if(name.length() >= 2);{
			this.name = name;
		}
	}
	public void setAge(int age) {
		// 나이의 0 ~ 150 사이만 가능하다.
		if(age >= 0 && age <= 150) {
			this.age = age;
		}
	}
	public void setHeight(double height) {
		// 키는 0 ~ 300 사이만 가능하다.
		if(height >= 0 && height <= 300) {
			this.height = height;
		}
	}
	public void setGender(char gender) {
		// 성별은 '남', '여'만 가능하다.
		if(gender == '남' || gender == '여') {
			this.gender = gender;
		}
	}
	public void setKorean(boolean isKorean) {
		this.isKorean = isKorean;
	}
	
	public String getName() {
		return name;
	}
	public int getAge() {
		return age;
	}
	public double getHeight() {
		return height;
	}
	public char getGender() {
		return gender;
	}
	public boolean isKorean() {
		return isKorean;
	}
	
}

PersonMain

package com.mywork.ex;

public class PersonMain {

	public static void main(String[] args) {
		
		Person woman = new Person();
		Person man = new Person("james", 20, 175.5, '남' );
		
		// woman.name = "alice";   //private 처리되었기 때문에 모든 field는 직접! 접근이 되지 않는다.
		woman.setName("alice");    // public 처리된 메소드 setName을 통해 우회! 접근만 가능
		woman.setAge(20);
		woman.setHeight(168.5);
		woman.setGender('여');
		
		System.out.println("성명 : " + woman.getName() + ", 나이 : " + woman.getAge() + ", 키 : " + woman.getHeight() + ", 성별 : " + woman.getGender());
		System.out.println("성명 : " + man.getName() + ", 나이 : " + man.getAge() + ", 키 : " + man.getHeight() + ", 성별 : " + man.getGender());
		
	}
	

}

Rect

package com.mywork.ex;

public class Rect {
	// 1. Fields
	private int width;
	private int height;
	private boolean isSquare;
	
	// Constructor
	public Rect(){
		this(1, 1);
	}
	public Rect(int side){
		this(side, side);
	}
	public Rect(int width, int height){
		this.width = width;
		this.height = height;
		this.isSquare = (width == height) ? true : false;
	}
	
	// Method
	public void output(){
		System.out.println("너비 : " + width);
		System.out.println("높이 : " + height);
		System.out.println("크기 : " + calcArea());
		System.out.println(isSquare ? "정사각형" : "직사각형");
	}
	private int calcArea() {
		return width + height;
	}
	
}

RectMain

package com.mywork.ex;

public class RectMain {

	public static void main(String[] args) {
		// 1. 객체(인스턴스) 생서
		// ==>>> 생성자가 호출된다!
		Rect nemo1 = new Rect();        // Rect(){} [Default(기본) 생성자] 
		                                //   -> 프로그래머가 만들지 않아도 자바가 자동으로 만들어준다.
		Rect nemo2 = new Rect(3);
		Rect nemo3 = new Rect(3, 5);
		
		// 2. 객체 메소드 호출
		nemo1.output();
		nemo2.output();
		nemo3.output();
	}

}

Student

package com.mywork.ex;

import java.util.Scanner;

public class Student {
	
	// Field
	private String name;
	private String dept;
	private String score1;
	private String score2;
	private double average;
	private boolean isPass;
	
	// Constructor
	public Student(String name, String dept) {
		this.name = name;
		this.dept = dept;
	}
	
	// Method
	public void input(Scanner scanner) {
		System.out.print("중간 >> ");
		score1 = scanner.nextLine();
		System.out.print("기말 >> ");
		score2 = scanner.nextLine();
		average = getAverage();
		isPass = isPass();
	}
	private double getAverage() {
		return (Double.parseDouble(score1) + Double.parseDouble(score2)) / 2;
	}
	private boolean isPass() {
		return average >= 80 ? true : false;
	}
	
	public void output() {
		System.out.println("이름 : " + name);
		System.out.println("학과 : " + dept);
		System.out.println("평균 : " + average);
		System.out.println("결과 : " + (isPass ? "합격" : "불합격"));
	}
	
}

StudentMain

package com.mywork.ex;

import java.util.Scanner;

public class StudentMain {

	public static void main(String[] args) {

		Student student = new Student("홍길동", "컴퓨터공학과");

		student.input(new Scanner(System.in));
		student.output();
		
	}

}
profile
시행착오, 문제해결 그 어디 즈음에.

0개의 댓글