학원에서 학습한 내용을 개인정리한 글입니다.

접근제한자 클래스명() {} -> 기본 생성자
public class D_ConstructorTest {
//생성자 선언하기
//접근제한자 클래스명() {} -> 기본 생성자
String data;
public D_ConstructorTest() {
System.out.println("기본 생성자 호출");
//필드 로직에 의한 기본값을 설정할 수 있음
if(C_InitialBlockTest.objCount == 0) {
data = "X";
} else {
data = "O";
}
}
}
public class D_ConstructorMain {
public static void main(String[] args) {
D_ConstructorTest ct = new D_ConstructorTest();
}
}
💡
Temi: 보통 클래스 안에 있는 생성자를 같은 이름으로 짓는지? 초기화용이라면 초기화용이라고 따로 빼는게 작업자가 알아보기 편할 것 같아서 물어봄
Teacher: 규칙임. 메소드랑은 다름. 문법이라 바꿀 수가 없음!
접근제한자 클래스명(변수1(매개변수), 변수2...) {} -> 매개변수 있는 생성자

//매개변수 있는 생성자
public D_ConstructorTest(String inputData) {
//매개변수에 전달된 값을 필드에 저장
this.data = inputData;
}
//타입을 보고 판단
//얘는 같은 String Type이라 불가!
//public D_ConstructorTest(String inputData) {
//
//}
public D_ConstructorTest(String inputData, int num) {
}
public class D_ConstructorMain {
public static void main(String[] args) {
D_ConstructorTest ct2 = new D_ConstructorTest("yap");
D_ConstructorTest ct3 = new D_ConstructorTest("새로운값");
System.out.println("data: " + ct2.data);
System.out.println("data: " + ct3.data);
}
}
💡
Temi: 생성자와 메소드 차이는 알았는데, 그럼 초기화 블럭과 생성자의 차이는?
Teacher: 생성자는 매개변수의 타입 차이 같은 것으로 골라쓸 수 있고 초기화블록은 new로 생성됐을 때 무조건 실행되는 차이가 있다. 이후 얘기하겠지만, 오버로딩에 대해서 배울 때 자세히 알려줄 것.
💡Temi: 생성자에 생성된 곳에 데이터 대입해주는 것은 초기 세팅이기만 한거고 나중에 넘버 수정은 메소드나 퍼블릭 데이터 수정으로 하면 되는건지??
Teacher: 맞음. 처음 생성할 때만 사용
//생성된 객체 주소를 저장하는 변수 -> 나, 자기자신
this.data = inputData;
//생성된 생성자 재활용하기
//this() 생성자 이용
public D_ConstructorTest(String data, int num, char gender) {
this(data, num);
this.gender = gender;
}
💡
Temi:
Teacher
//minhyuk 12345 minhyuk@minhyuk.com 21 코딩,러닝,편식
public Member() {
}
//user03,3333 없음, 0, null
public Member(String id, String pw, String email, int age, String[] hobby) {
this.userId = id;
this.userPw = pw;
this.userEmail = email;
this.userAge = age;
this.userHobby = hobby;
System.out.printf(printFormatAll,
this.userId,
this.userPw,
this.userEmail,
this.userAge,
Arrays.toString(this.userHobby));
}
public Member(String id, String pw) {
this.userId = id;
this.userPw = pw;
System.out.printf(printFormatAll,
this.userId,
this.userPw,
this.userEmail,
this.userAge,
Arrays.toString(this.userHobby));
}
//user04,4444 없음, 0, 운동,코딩,산책
public Member(String id, String pw, String[] hobby) {
this.userId = id;
this.userPw = pw;
this.userHobby = hobby;
System.out.printf(printFormatAll,
this.userId,
this.userPw,
this.userEmail,
this.userAge,
Arrays.toString(this.userHobby));
}
public Member(String id, String pw, String email, int age, String[] hobby) {
this.userId = id;
//프로그램 정지
if (pw.length() < 8) {
throw new IllegalArgumentException("비밀번호를 8글자이상 입력하세요");
} else {
this.userPw = pw;
}
this.userEmail = email;
this.userAge = age;
this.userHobby = hobby;
System.out.printf(printFormatAll, this.userId, this.userPw, this.userEmail, this.userAge, Arrays.toString(this.userHobby));
}

public class MyMethod {
//메소드 선언
//접근 제한자(public), 반환형(기본, 참조형, void), 메소드명([매개변수]) {로직}
//유형별 메소드 선언
//1 반환형이 없고 매개변수 없는 메소드
public void test1() {
System.out.println("반환형이 없고 매개변수 없는 메소드");
}
}
public static void main(String[] args) {
//메소드 이용하기
MyMethod myMethod = new MyMethod();
myMethod.test1();
}
//2 반환형이 없고 매개변수 있는 메소드
public void test2(String msg) {
System.out.println("반환형이 없고 매개변수 있는 메소드: "+ msg);
public class E_MethodMain {
public static void main(String[] args) {
//메소드 이용하기
MyMethod myMethod = new MyMethod();
myMethod.test2("흐어");
}
}
//메소드의 반환형을 설정하면 반드시 {}내부에
//return 예약어를 이용해서 반환형으로 선언한 타입의 값을 반환줘야함.
public int test3() {
Scanner sc = new Scanner(System.in);
int su = sc.nextInt();
if (su > 0) return su;
else return 0;
}
public static void main(String[] args) {
//메소드 이용하기
MyMethod myMethod = new MyMethod();
int result = myMethod.test3();
}
public long test4(int su1, int su2) {
su1 += 200;
su2 *= 10;
return su1 * su2;
}
public static void main(String[] args) {
//메소드 이용하기
MyMethod myMethod = new MyMethod();
long result1 = myMethod.test4(4, 3);
}

//매개변수, 반환형에 참조형 타입 선언하기
public void test5(int num) {
num *= 100;
}
public void test6(int[] num) {
num[0] *= 100;
}
//메소드의 에약어
//Static
public static void test8() {
System.out.println("static 메소드 실행 : ");
}
public static void main(String[] args) {
MyMethod.test8();
}
public class FieldUseMethod {
private int no;
private String name;
public FieldUseMethod(int no, String name) {
this.no = no;
this.name = name;
}
public String infoObject() {
return this.no + " " + this.name;
}
public void incrementNo() {
this.no++;
}
public void incrementByInputNum(int no) {
this.no += no;
}
}
public static void main(String[] args) {
//필드를 이용하는 메소드
FieldUseMethod fum = new FieldUseMethod(1, "ㅇㅇㅇ");
System.out.println(fum.infoObject());
fum.incrementNo();
System.out.println(fum.infoObject());
FieldUseMethod fum1 = new FieldUseMethod(55, "ㅁㅁ");
System.out.println(fum1.infoObject());
fum1.incrementByInputNum(10);
System.out.println(fum1.infoObject());
}
💡
Temi: 매개 변수에 int num || String a 같은 식으로 넣을 수 있는지?
Teacher: 안됨. 선언도 안됨. 정적타입이라 불가. 대신 타입이 처음부터 정해져있기 때문에 다른 언어보다 안정적.
public class Product {
private String productName;
private int productPrice;
private int productCategory;
public void setProductName(String name) {
this.productName = name;
}
public String getProductName() {
return this.productName;
}
}
//Main getter setter 이용
Product p = new Product();
p.setProductName("휴대폰");
System.out.println(p.getProductName());
public class Product {
private int productPrice, productInventory;
private double productDiscountPercent;
private String productType, productName;
public static int productNum = 0;
public Product() {
}
// 타입, 이름, 가격만 설정가능
public Product(String productType, String productName, int productPrice){
this.productType = productType;
this.productName = productName;
this.productPrice = productPrice;
}
// 타입, 이름, 가격, 할인률 설정가능
public Product(String productType, String productName, int productPrice, double productDiscountPercent) {
this(productType, productName, productPrice);
this.productDiscountPercent = productDiscountPercent;
}
// 이름, 가격, 할인률, 재고 설정가능
public Product(String productName, int productPrice, double productDiscountPercent, int productInventory) {
this.productName = productName;
this.productPrice = productPrice;
this.productDiscountPercent = productDiscountPercent;
this.productInventory = productInventory;
}
private String printIntType(int num) {
String result = "";
result = (num != 0 ? (", " + num) : "");
return result;
}
private String printDoubleType(double num) {
String result = "";
result = (num != 0 ? (", " + num) : "");
return result;
}
//TODO: 여긴 하드코딩처럼 분기점 나누는거 말곤 지금 당장 생각이 X
private String printStringType(String productType, String productName, boolean isProductName) {
String result = "";
if ((productType != null) && (productName != null)) {
//productType 일 때
if (isProductName == false) {
result = productType;
//productName 일 때
} else {
result = ", " + productName;
}
} else if ((productType == null) && (productName != null)) {
//productType 일 때
if (isProductName == false) {
result = "";
//productName 일 때
} else {
result = productName;
}
//그 외
} else {
return "404";
}
return result;
}
public void printProductInfo() {
System.out.println(
printStringType(this.productType, this.productName, false) +
printStringType(this.productType, this.productName, true) +
printIntType(this.productPrice) +
printDoubleType(this.productDiscountPercent) +
printIntType(this.productInventory));
}
}
package com.myobj.run;
import com.myobj.vo.Product;
public class Main {
public static void main(String[] Args) {
Product pdComputer = new Product("컴퓨터", "maxbook", 200);
Product.productNum++;
System.out.print(Product.productNum + " ");
pdComputer.printProductInfo();
Product pdPhone = new Product("핸드폰", "갤럭시노트", 120, 0.2);
Product.productNum++;
System.out.print(Product.productNum + " ");
pdPhone.printProductInfo();
Product pdMask = new Product("마스크", 10, 0.5, 100);
Product.productNum++;
System.out.print(Product.productNum + " ");
pdMask.printProductInfo();
}
}
