210708 목
Chap3. 필드
1. 필드
1) 변수
(1) 전역변수
1> 멤버 변수(인스턴스 변수)
-생성 : new를 통해 인스턴스(객체) 생성 시 메모리 할당
-소멸 : 객체 소멸 시 소멸
2> 클래스 변수(static 변수)
: static 예약어가 붙은 변수
-생성 : 프로그램 실행 시 static 메모리 영역에 할당
-소멸 : 프로그램이 종료 될 때 소멸
(2) 지역 변수
: 메소드 실행 시, 생성자, 제어문 등 클래스 영역을 제외한 특정한 구역
-({}) 안에 생성 되어 그 지역에서만 사용 가능
-생성 : 특정한 구역 ({}) 실행 시 메모리 영역에 할당(ex. 메소드 실행 시)
-소멸 : 특정한 구역 ({}) 종료 시 소멸(ex. 메소드 종료 시)
<멤버 변수, 지역 변수, 매개 변수 Test>
public class FieldTest2 {
// 필드부 / 멤버 변수(인스턴스 변수)
private int global;
//생성자
public FieldTest2(){}
//매개변수가 있는 메소드
public void test(int num) {
//지역변수 (특정 구역 내에 작성하는 변수)
//지역 변수에는 접근 제한자를 쓰지 않는다
int local = 10;
// 멤버 변수 출력
// 전역 변수는 초기화 하지 않았을 떄 JVM이 기본값을 부여
// 전역 변수는 클래스 전역에서 사용 가능
System.out.println("전역 변수 : " + global);
//지역변수 출력
//지역변수는 반드시 초기화 되어야 함
System.out.println("지역 변수 : " + local);
//매개변수 출력
//매개변수는 메소드 호출 시 반드시 값이 전달되어 오기 때문에 사용 가능
System.out.println("매개 변수 : " + num);
public class Run {
public static void main(String[] args) {
//2. FieldTest2
FieldTest2 ft2 = new FieldTest2();
ft2.test(20);
}
}
답 전역 변수 : 0 지역 변수 : 10 매개 변수 : 20 |
*매개 변수의 용도
input 값, 어떤 식을 실행시켜주기 위한 설정값이다
예)
public int multiply(int a, int b) {
return a * b;
System.out.println(ft2.multiply(10, 20));
System.out.println(ft2.multiply(30, 40));
답 200 1200 |
2. 예약어
1) static
: 같은 타입의 여러 객체가 공유할 목적의 필드에 사용하며, 프로그램 start시에 정적 메모리(static) 영역에 자동 할당되는 멤버에 적용
<public static, private static 입력>
public class FieldTest3 {
//전역 변수의 일종인 클래스 변수는 static 예약어가 붙은 변수
//static 키워드가 붙으면 프로그램을 실행하자 마자 static 메모리 영역에 할당됨
public static String pubSta = "public static";
private static String priSta = "private static";
public FieldTest3(){}
//private를 위한 getter/setter 메소드
public static void setPriSta(String priSta) {
FieldTest3.priSta = priSta;
//모든 객체들이 "공유"하는 자원으로 객체 생성 없이
//프로그램 실행하자마자 static 영역에 할당
}
public static String getPriSta() {
return priSta;
}
<실행>
//3. FieldTest3
//FieldTest3 ft3 = new FieldTest3();
//=> static을 사용하기 위해서는 객체 생성 불필요
//1) public static
System.out.println(FieldTest3.pubSta);
FieldTest3.pubSta = "changed public static";
System.out.println(FieldTest3.pubSta);
// 객체 생성 필요 없이 바로 클래스명. 으로 접근 가능
//2) private static
System.out.println(FieldTest3.getPriSta());
FieldTest3.setPriSta("changed private static");
System.out.println(FieldTest3.getPriSta());
답 public static changed public static private static changed private static |
2) final
: 하나의 값만 계속 저장해야 하는 변수에 사용하는 예약어.
-한번 초기화하고 나면 변경할 수 없다.
*상수 필드
: public에 static과 final 예약어를 모두 사용하는 것.
-반드시 선언과 동시에 값 초기화한다.
-프로그램 시작 시 값이 저장되면 더 이상 변경하지 않고 공유하면서 사용할 목적이다.
예)
public class FieldTest4 {
public static final int NUM = 1 ;
}
System.out.println(FieldTest4.NUM);
답 1 |
3. 초기화
1) 순서
<Static 변수 초기화, 인스턴스 변수>
public class Product {
// 멤버 변수
private String pName = "아이폰11";
private int price = 786600;
//클래스 변수
private static String brand = "애플";
//인스턴스 블록 : 인스턴스 변수를 초기화 시키는 블럭으로 객체 생성을 할때 마다 실행
{
pName = "cyon";
price = 200000;
brand = "엘지";
// => 인스턴스 블럭에서는 static 필드도 초기화 가능
//하지만 static 초기화 블럭은 프로그램 시작 시에 초기화를 하기 때문에
//객체 생성 이후 값을 초기화 하는 인스턴스 초기화 블럭의 값으로 덮어쓰게 됨
}
//static 블록 : 클래스 변수를 초기화 시키는 블럭으로 프로그램 시작 시 단 한번 실행
static {
brand = "사과";
}
답 Product [pName =cyon, price=200000, brand=엘지] |
Chap04 생성자
1. 생성자
: 객체가 new 연산자를 통해 Heap 메모리 영역에 할당될 때 객체 안에서 만들어지는 필드 초기화, 필드 생성 시 필요한 기능 수행
1) 규칙
생성자의 선언은 메소드와 유사하나 반환 값이 없으며 생성자 명을 클래스 명과 똑같이 지정해 주어야 함
2) 기본 생성자
생성자를 작성하지 않은 경우, 클래스 사용 시 JVM이 자동으로 기본 생성자 생성
3) 매개변수 생성자
-매개변수 생성자 작성시 JVM이 기본 생성자를 자동으로 생성해주지 않음. 따라서 기본 생성자를 미리 지정해주는 것이 좋음.
<기본 생성자 출력>
public class User {
private String userId;
private String userPwd;
private String userName;
private int age;
private char gender;
public User() {
}
public String information() {
return "[userId=" + userId + ", userPwd=" + userPwd +
", useName=" + userName + ", age=" + age +
", gender=" + gender + "]";
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
User u1 = new User();
System.out.println(u1.information());
답 [userId=null, userPwd=null, useName=null, age=0, gender= |
=> 이것을 통해서 기본생성자가 객체를 생성한다는 것을 알 수 있다.
public class User {
private String userId;
private String userPwd;
private String userName;
private int age;
private char gender;
public User() {
//단지 객체 생성을 위해 사용
//클래스 내 생성자가 0개일 경우 JVM이 자동으로 기본 생성자 생성
}
//매개변수 생성자
// => 객체 생성과 동시에 매개변수로 전달 된 값들을 해당 멤버에 초기화 하는 목적
public User(String userId, String userPwd, String userName) {
this.userId = userId;
this.userPwd = userPwd;
this.userName = userName;
}
//출력을 위한 메소드
public String information() {
return "[userId=" + userId + ", userPwd=" + userPwd +
", useName=" + userName + ", age=" + age +
", gender=" + gender + "]";
}
}
User u2 = new User("user02", "pass02", "홍길동");
System.out.println(u2.information());
답 [userId=user02, userPwd=pass02, useName=홍길동, age=0, gender= ] |
<매개변수를 다양하게 작성>
package com.kh.chap06_constructor.model.vo;
public class User {
/*
* 생성자 사용 목적
* 1. 객체를 생성 해주기 위한 목적
* 2. 매개 변수로 전달 받은 값을 필드에 초기화할 목적
*/
/*생성자 사용시 주의사항
* 1. 반드시 클래스명과 동일해야 함(대/소문자 구분)
* 2. 반환형이 존재하지 않음
* 3. 매개변수 생성자 작성 시 기본 생성자는 반드시 작성해야 함
*
*/
private String userId;
private String userPwd;
private String userName;
private int age;
private char gender;
public User() {
//단지 객체 생성을 위해 사용
//클래스 내 생성자가 0개일 경우 JVM이 자동으로 기본 생성자 생성
}
//매개변수 생성자
// => 객체 생성과 동시에 매개변수로 전달 된 값들을 해당 멤버에 초기화 하는 목적
public User(String userId, String userPwd, String userName) {
this.userId = userId;
this.userPwd = userPwd;
this.userName = userName;
}
//매개변수 생성자는 매개 변수를 달리하면 다양한 패턴으로 작성 가능
public User(String userId, String userPwd,
String userName, int age, char gender) {
this.userId = userId;
this.userPwd = userPwd;
this.userName = userName;
this.age = age;
this.gender = gender;
//this(userId, userPwd, userName);
//위와 같이 중복되는 동일한 초기화를 하는 내용의 생성자가 존재할 경우
// this() 생성자 사용 가능
// 같은 클래스 내에서는 생성자에서 다른 생성자 호출 가능
// 단 이 때 반드시 첫 줄에 작성해야 함
//this.age = age;
//this.gender = gender;
}
/*getter/setter 있어야 하지만 생략*/
//출력을 위한 메소드
public String information() {
return "[userId=" + userId + ", userPwd=" + userPwd +
", useName=" + userName + ", age=" + age +
", gender=" + gender + "]";
}
}
User u3 = new User("user03", "pass03", "부승관", 20, 'F');
System.out.println(u3.information());
답 [userId=user03, userPwd=pass03, useName=부승관, age=20, gender=F] |
*오버로딩
: 한 클래스 내에 동일한 이름의 메소드를 여러개 작성한 기법
'웹개발 수업 > JAVA' 카테고리의 다른 글
[Day +14]상속 / 오버라이딩, 오버로딩, for each문 (0) | 2021.07.12 |
---|---|
[Day +13]객체 / 오버로딩, 메소드, 객체배열 (0) | 2021.07.11 |
[Day +11]객체 / 객체지향언어, 클래스, 캡슐화, 추상화, 접근 제한자, 필드 (0) | 2021.07.11 |
[Day +9]배열2 (0) | 2021.07.11 |
[Day +8] 배열1 (0) | 2021.07.11 |