목차
package kr.s10.object.capsule;
class Capsule{
//private은 같은 클래스 내에서만 접근이 가능함.
//int a = 10; //defalt
private int a;
public void setA(int n) {
if(n >=0) {
a = n;
}else {
System.out.println("음수는 허용되지 않습니다.");
}
}
public int getA() {
return a;
}
}
public class CapsuleMain {
public static void main(String[] args) {
Capsule cap = new Capsule();
//변수 a의 접근 지정자(제한자)가 private 이기 때문에
//같은 클래스에서는 호출이 가능하지만 다른 클래스에서는
//호출 불가능
//System.out.println(cap.a);
//변수 a의 접근 지정자 (제한자)가 private이기 떄문에
//같은 클래스에서는 호출이 가능하지만 다른 클래스에서는 호출 불가능
cap.setA(-10);
System.out.println(cap.getA());
}
}
음수는 허용되지 않습니다.
0
실습
package kr.s11.object.constructor;
class Car{
String color;
String gearType;
int door;
//생성자
public Car() {}
}
public class CarMain01 {
public static void main(String[] args) {
//생성자는 객체 생성시 단 한 번만 실행되고 객체 생성 이후에는 호출 불가능
//맴버 변수를 초기화하는 역할 수행
Car c1 = new Car();
System.out.println(c1.color + ", " + c1.gearType + ", " + c1.door);
//객체의 맴버 변수에 값을 할당
c1.color = "red";
c1.gearType = "auto";
c1.door = 5;
System.out.println(c1.color + ", " + c1.gearType + ", " + c1.door);
}
}
null, null, 0
red, auto, 5
package kr.s11.object.constructor;
class Car2{
String color;
String gearType;
int door;
//생성자 오버로딩
//생성자를 여러개 정의하는데 인자의 타입과 개수, 배치 순서를 기준으로
//생성자를 구분
public Car2() {}
public Car2(String c, String d, int g) {
color =c;
gearType =d;
door =g;
}
}
public class CarMain02 {
public static void main(String[] args) {
Car2 car = new Car2();
car.color = "골드";
car.gearType = "auto";
car.door = 5;
System.out.println(car.color + "," + car.gearType + ","+ car.door);
Car2 car2 = new Car2("검정색","manual",4);
System.out.println(car2.color + "," + car2.gearType + ","+ car2.door);
}
}
골드,auto,5
검정색,manual,4
package kr.s11.object.constructor;
class Student {
int korean;
int english;
int math;
int history;
int science;
int num; //과목수
//생성자 오버로딩
public Student (int k, int e, int m) {
korean =k;
english = e;
math = m;
num = 3;// 과목수 지정
}
public Student(int k, int e, int m, int h , int s) {
korean =k;
english = e;
math = m;
history = h;
science = s;
num = 5; //과목수 지정
}
//총점 구하기
public int getTotal() {
int total;
if (num ==3) {//3과목
total = korean + english+math;
}else {//5과목
total = korean + english+math+history+science;
}
return total;
}
//평균 구하기
public int getAverage() {
return getTotal()/num;
}
}
public class StudentMain {
public static void main(String[] args) {
//3과목 시험 보기
Student s1 = new Student(90,97,95);
System.out.println("합계:"+ s1.getTotal());
System.out.println("평균:"+ s1.getAverage());
System.out.println("======================");
//5과목 시험보기
Student s2 = new Student(88,82,84,87,90);
System.out.println("합계:"+ s2.getTotal());
System.out.println("평균:"+ s2.getAverage());
System.out.println("======================");
}
}
합계:282
평균:94
======================
합계:431
평균:86
======================
package kr.s12.object.constructor;
public class AccountMain {
String accountNo; //계좌번호
String ownerName; //예금주
int balance; //잔고
//위에 class와 명칭이 일치해야지 생성자를 정의할 수 있음.
public AccountMain(String a , String o, int b){
accountNo = a;
ownerName = o;
balance = b;
System.out.println(ownerName + "님 계좌가 개설되었습니다.");
}
//예금하기
public void deposit(int amount) {
if(amount <=0) {
System.out.println("0보다 크게 입력해야 합니다.");
//void형 메서드에서 특정 조건일 때 메서드를 빠져나감(메서드 종료)
//else를 만들지 않아도 가능함.
return;
}
balance += amount;
System.out.println("입금이 완료되었습니다.");
}
//출금하기
public void withdraw(int amount) {
if(amount <=0) {
System.out.println("0보다 크게 입력해야 합니다.");
return;
}
if(balance < amount) {
System.out.println("잔고가 부족합니다.");
return;
}
balance -= amount;
System.out.println(amount+"원이 출금이 완료되었습니다.");
}
public static void main(String[] args) {
//계좌 생성
AccountMain account1 =
new AccountMain("123-456","홍길동",10000);
System.out.println("계좌번호 :" + account1.accountNo);
System.out.println("예금주 : " + account1.ownerName);
System.out.printf("잔고 : %,d원%n",account1.balance);
System.out.println("============================");
//예금하기
account1.deposit(5000);
//출금하기
account1.withdraw(10000);
System.out.println("계좌번호 :" + account1.accountNo);
System.out.println("예금주 : " + account1.ownerName);
System.out.printf("잔고 : %,d원%n",account1.balance);
}
}
홍길동님 계좌가 개설되었습니다.
계좌번호 :123-456
예금주 : 홍길동
잔고 : 10,000원
============================
입금이 완료되었습니다.
10000원이 출금이 완료되었습니다.
계좌번호 :123-456
예금주 : 홍길동
잔고 : 5,000원
package kr.s13.object.array;
class Book{
private String category;
private String name;
private int price;
private double discount;
//생성자
public Book(String c , String n ,int p ,double d) {
category = c;
name = n;
price = p;
discount = d;
}
//private 때문에 캡슐화 시킴
public String getCategory() {
return category;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public double getDiscount() {
return discount;
}
}
public class BookMain {
public static void main(String[] args) {
Book[] bookArray = new Book[3];
//Book 객체를 3개 생성하여 배열에 저장
bookArray[0] = new Book("IT","Java",50000,0.05);
bookArray[1] = new Book("IT","Oracle",40000,0.03);
bookArray[2] = new Book("미술","반고흐",60000,0.06);
//반복문을 이용해서 객체의 요소 출력
for(int i =0; i<bookArray.length ; i++) {
System.out.printf("%s\\t ",bookArray[i].getCategory());
System.out.printf("%s\\t ",bookArray[i].getName());
System.out.printf("%,d원\\t ",bookArray[i].getPrice());
System.out.printf("%.2f%n",bookArray[i].getDiscount());
}
}
}
IT Java 50,000원 0.05
IT Oracle 40,000원 0.03
미술 반고흐 60,000원 0.06
package kr.s13.object.array;
public class Score {
//은닉화
private String name;
private int korean;
private int english;
private int math;
/*
//생성자
public Score(String n, int k, int e, int m) {
name = n;
korean = k;
english = e;
math =m;
}
*/
//생성자 this를 사용
public Score(String name, int korean, int english, int math) {
//멤버변수 = 지역변수
this.name = name;
this.korean = korean;
this.english = english;
this.math =math;
}
//총점 구하기
public int makeSum() {
return korean+english+math;
}
//평균 구하기
public int makeAvg () {
return makeSum()/3;
}
//등급 구하기
public String makeGrade() {
String grade;
switch(makeAvg()/10) {
case 10:
case 9:
return "A"; //grade = "A"; break;
case 8:
return "B";//grade = "B"; break;
case 7:
return "C";//grade = "C"; break;
case 6:
return "D";//grade = "D"; break;
default :
return "F";//grade = "F";
}
//return grade;
}
public String getName() {
return name;
}
public int getKorean() {
return korean;
}
public int getEnglish() {
return english;
}
public int getMath() {
return math;
}
}
package kr.s13.object.array;
public class ScoreMain {
public static void main(String[] args) {
Score[] scoreArray = new Score[3]; //scoreArray는 배열의 주소를 나타내고 알려준다.
scoreArray[0] = new Score("홍길순",99,98,97);
scoreArray[1] = new Score("박문수",89,91,92);
scoreArray[2] = new Score("장영실",79,81,85);
//반복문을 이용한 배열의 요소 출력
System.out.println("이 름 국어 영어 수학 총 점 평균 등급");
System.out.println("=============================");
for (int i =0; i<scoreArray.length; i++) {
System.out.printf("%s ",scoreArray[i].getName());
System.out.printf("%d ",scoreArray[i].getKorean());
System.out.printf("%d ",scoreArray[i].getEnglish());
System.out.printf("%d ",scoreArray[i].getMath());
System.out.printf("%d ",scoreArray[i].makeSum());
System.out.printf("%d ",scoreArray[i].makeAvg());
System.out.printf("%s%n",scoreArray[i].makeGrade());
}
System.out.println("-----------------------------");
for(Score s : scoreArray) {
System.out.printf("%s ", s.getName());
System.out.printf("%d ", s.getKorean());
System.out.printf("%d ", s.getEnglish());
System.out.printf("%d ", s.getMath());
System.out.printf("%d ", s.makeSum());
System.out.printf("%d ", s.makeAvg());
System.out.printf("%s%n", s.makeGrade());
}
//확장for문을 이용한 배열의 요소 출력
}
}
이 름 국어 영어 수학 총 점 평균 등급
=============================
홍길순 99 98 97 294 98 A
박문수 89 91 92 272 90 A
장영실 79 81 85 245 81 B
-----------------------------
홍길순 99 98 97 294 98 A
박문수 89 91 92 272 90 A
장영실 79 81 85 245 81 B
'쌍용교육(JAVA) > JAVA' 카테고리의 다른 글
쌍용교육 -JAVA 수업 9일차 LocalVariable(멤버,지역변수) (0) | 2024.04.11 |
---|---|
쌍용교육 -JAVA 수업 9일차 Static 및 응용 (0) | 2024.04.11 |
쌍용교육 -JAVA 수업 8일차 Pack (0) | 2024.04.11 |
쌍용교육 -JAVA 수업 8일차 Overloading (0) | 2024.04.11 |
쌍용교육 -JAVA 수업 7~8일차 Method (0) | 2024.04.11 |
package kr.s10.object.capsule;
class Capsule{
//private은 같은 클래스 내에서만 접근이 가능함.
//int a = 10; //defalt
private int a;
public void setA(int n) {
if(n >=0) {
a = n;
}else {
System.out.println("음수는 허용되지 않습니다.");
}
}
public int getA() {
return a;
}
}
public class CapsuleMain {
public static void main(String[] args) {
Capsule cap = new Capsule();
//변수 a의 접근 지정자(제한자)가 private 이기 때문에
//같은 클래스에서는 호출이 가능하지만 다른 클래스에서는
//호출 불가능
//System.out.println(cap.a);
//변수 a의 접근 지정자 (제한자)가 private이기 떄문에
//같은 클래스에서는 호출이 가능하지만 다른 클래스에서는 호출 불가능
cap.setA(-10);
System.out.println(cap.getA());
}
}
음수는 허용되지 않습니다.
0
실습
package kr.s11.object.constructor;
class Car{
String color;
String gearType;
int door;
//생성자
public Car() {}
}
public class CarMain01 {
public static void main(String[] args) {
//생성자는 객체 생성시 단 한 번만 실행되고 객체 생성 이후에는 호출 불가능
//맴버 변수를 초기화하는 역할 수행
Car c1 = new Car();
System.out.println(c1.color + ", " + c1.gearType + ", " + c1.door);
//객체의 맴버 변수에 값을 할당
c1.color = "red";
c1.gearType = "auto";
c1.door = 5;
System.out.println(c1.color + ", " + c1.gearType + ", " + c1.door);
}
}
null, null, 0
red, auto, 5
package kr.s11.object.constructor;
class Car2{
String color;
String gearType;
int door;
//생성자 오버로딩
//생성자를 여러개 정의하는데 인자의 타입과 개수, 배치 순서를 기준으로
//생성자를 구분
public Car2() {}
public Car2(String c, String d, int g) {
color =c;
gearType =d;
door =g;
}
}
public class CarMain02 {
public static void main(String[] args) {
Car2 car = new Car2();
car.color = "골드";
car.gearType = "auto";
car.door = 5;
System.out.println(car.color + "," + car.gearType + ","+ car.door);
Car2 car2 = new Car2("검정색","manual",4);
System.out.println(car2.color + "," + car2.gearType + ","+ car2.door);
}
}
골드,auto,5
검정색,manual,4
package kr.s11.object.constructor;
class Student {
int korean;
int english;
int math;
int history;
int science;
int num; //과목수
//생성자 오버로딩
public Student (int k, int e, int m) {
korean =k;
english = e;
math = m;
num = 3;// 과목수 지정
}
public Student(int k, int e, int m, int h , int s) {
korean =k;
english = e;
math = m;
history = h;
science = s;
num = 5; //과목수 지정
}
//총점 구하기
public int getTotal() {
int total;
if (num ==3) {//3과목
total = korean + english+math;
}else {//5과목
total = korean + english+math+history+science;
}
return total;
}
//평균 구하기
public int getAverage() {
return getTotal()/num;
}
}
public class StudentMain {
public static void main(String[] args) {
//3과목 시험 보기
Student s1 = new Student(90,97,95);
System.out.println("합계:"+ s1.getTotal());
System.out.println("평균:"+ s1.getAverage());
System.out.println("======================");
//5과목 시험보기
Student s2 = new Student(88,82,84,87,90);
System.out.println("합계:"+ s2.getTotal());
System.out.println("평균:"+ s2.getAverage());
System.out.println("======================");
}
}
합계:282
평균:94
======================
합계:431
평균:86
======================
package kr.s12.object.constructor;
public class AccountMain {
String accountNo; //계좌번호
String ownerName; //예금주
int balance; //잔고
//위에 class와 명칭이 일치해야지 생성자를 정의할 수 있음.
public AccountMain(String a , String o, int b){
accountNo = a;
ownerName = o;
balance = b;
System.out.println(ownerName + "님 계좌가 개설되었습니다.");
}
//예금하기
public void deposit(int amount) {
if(amount <=0) {
System.out.println("0보다 크게 입력해야 합니다.");
//void형 메서드에서 특정 조건일 때 메서드를 빠져나감(메서드 종료)
//else를 만들지 않아도 가능함.
return;
}
balance += amount;
System.out.println("입금이 완료되었습니다.");
}
//출금하기
public void withdraw(int amount) {
if(amount <=0) {
System.out.println("0보다 크게 입력해야 합니다.");
return;
}
if(balance < amount) {
System.out.println("잔고가 부족합니다.");
return;
}
balance -= amount;
System.out.println(amount+"원이 출금이 완료되었습니다.");
}
public static void main(String[] args) {
//계좌 생성
AccountMain account1 =
new AccountMain("123-456","홍길동",10000);
System.out.println("계좌번호 :" + account1.accountNo);
System.out.println("예금주 : " + account1.ownerName);
System.out.printf("잔고 : %,d원%n",account1.balance);
System.out.println("============================");
//예금하기
account1.deposit(5000);
//출금하기
account1.withdraw(10000);
System.out.println("계좌번호 :" + account1.accountNo);
System.out.println("예금주 : " + account1.ownerName);
System.out.printf("잔고 : %,d원%n",account1.balance);
}
}
홍길동님 계좌가 개설되었습니다.
계좌번호 :123-456
예금주 : 홍길동
잔고 : 10,000원
============================
입금이 완료되었습니다.
10000원이 출금이 완료되었습니다.
계좌번호 :123-456
예금주 : 홍길동
잔고 : 5,000원
package kr.s13.object.array;
class Book{
private String category;
private String name;
private int price;
private double discount;
//생성자
public Book(String c , String n ,int p ,double d) {
category = c;
name = n;
price = p;
discount = d;
}
//private 때문에 캡슐화 시킴
public String getCategory() {
return category;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public double getDiscount() {
return discount;
}
}
public class BookMain {
public static void main(String[] args) {
Book[] bookArray = new Book[3];
//Book 객체를 3개 생성하여 배열에 저장
bookArray[0] = new Book("IT","Java",50000,0.05);
bookArray[1] = new Book("IT","Oracle",40000,0.03);
bookArray[2] = new Book("미술","반고흐",60000,0.06);
//반복문을 이용해서 객체의 요소 출력
for(int i =0; i<bookArray.length ; i++) {
System.out.printf("%s\\t ",bookArray[i].getCategory());
System.out.printf("%s\\t ",bookArray[i].getName());
System.out.printf("%,d원\\t ",bookArray[i].getPrice());
System.out.printf("%.2f%n",bookArray[i].getDiscount());
}
}
}
IT Java 50,000원 0.05
IT Oracle 40,000원 0.03
미술 반고흐 60,000원 0.06
package kr.s13.object.array;
public class Score {
//은닉화
private String name;
private int korean;
private int english;
private int math;
/*
//생성자
public Score(String n, int k, int e, int m) {
name = n;
korean = k;
english = e;
math =m;
}
*/
//생성자 this를 사용
public Score(String name, int korean, int english, int math) {
//멤버변수 = 지역변수
this.name = name;
this.korean = korean;
this.english = english;
this.math =math;
}
//총점 구하기
public int makeSum() {
return korean+english+math;
}
//평균 구하기
public int makeAvg () {
return makeSum()/3;
}
//등급 구하기
public String makeGrade() {
String grade;
switch(makeAvg()/10) {
case 10:
case 9:
return "A"; //grade = "A"; break;
case 8:
return "B";//grade = "B"; break;
case 7:
return "C";//grade = "C"; break;
case 6:
return "D";//grade = "D"; break;
default :
return "F";//grade = "F";
}
//return grade;
}
public String getName() {
return name;
}
public int getKorean() {
return korean;
}
public int getEnglish() {
return english;
}
public int getMath() {
return math;
}
}
package kr.s13.object.array;
public class ScoreMain {
public static void main(String[] args) {
Score[] scoreArray = new Score[3]; //scoreArray는 배열의 주소를 나타내고 알려준다.
scoreArray[0] = new Score("홍길순",99,98,97);
scoreArray[1] = new Score("박문수",89,91,92);
scoreArray[2] = new Score("장영실",79,81,85);
//반복문을 이용한 배열의 요소 출력
System.out.println("이 름 국어 영어 수학 총 점 평균 등급");
System.out.println("=============================");
for (int i =0; i<scoreArray.length; i++) {
System.out.printf("%s ",scoreArray[i].getName());
System.out.printf("%d ",scoreArray[i].getKorean());
System.out.printf("%d ",scoreArray[i].getEnglish());
System.out.printf("%d ",scoreArray[i].getMath());
System.out.printf("%d ",scoreArray[i].makeSum());
System.out.printf("%d ",scoreArray[i].makeAvg());
System.out.printf("%s%n",scoreArray[i].makeGrade());
}
System.out.println("-----------------------------");
for(Score s : scoreArray) {
System.out.printf("%s ", s.getName());
System.out.printf("%d ", s.getKorean());
System.out.printf("%d ", s.getEnglish());
System.out.printf("%d ", s.getMath());
System.out.printf("%d ", s.makeSum());
System.out.printf("%d ", s.makeAvg());
System.out.printf("%s%n", s.makeGrade());
}
//확장for문을 이용한 배열의 요소 출력
}
}
이 름 국어 영어 수학 총 점 평균 등급
=============================
홍길순 99 98 97 294 98 A
박문수 89 91 92 272 90 A
장영실 79 81 85 245 81 B
-----------------------------
홍길순 99 98 97 294 98 A
박문수 89 91 92 272 90 A
장영실 79 81 85 245 81 B
'쌍용교육(JAVA) > JAVA' 카테고리의 다른 글
쌍용교육 -JAVA 수업 9일차 LocalVariable(멤버,지역변수) (0) | 2024.04.11 |
---|---|
쌍용교육 -JAVA 수업 9일차 Static 및 응용 (0) | 2024.04.11 |
쌍용교육 -JAVA 수업 8일차 Pack (0) | 2024.04.11 |
쌍용교육 -JAVA 수업 8일차 Overloading (0) | 2024.04.11 |
쌍용교육 -JAVA 수업 7~8일차 Method (0) | 2024.04.11 |