-
인스턴스 멤버의 사용 - 클래스파일
public class ClassEx1 {
//필드 즉 속성 현재는 인스턴스 필드
int i ;
Integer j;
char[] charArr;
String str;
//생성자
public ClassEx1() {
}
// 파라미터를 가진 생성자를 주면 기본 생성자는 자동 생성되지 않는다.
ClassEx1(int i){
}
// 메소드 현재는 인스턴스 메서드
void method1() {
}
void method2() {
}
}
-
인스턴스 멤버의 사용 - 메인메서드
public class MainEx {
public static void main(String[] args) {
new ClassEx1();//인스턴스 생성 후 주소 할당이 안된 상태
ClassEx1 a = new ClassEx1();//타입 선언 및 참조변수 선언 으로 주소 값 대입
// System.out.println(a.i);
// System.out.println(a.j);
// System.out.println(a.charArr);
// System.out.println(a.str);
a.method1();
a.method2();
//필드와 메소드도 전부 호출 가능
ClassEx1 b = a;//call by reference 즉 한 인스턴스에 2개의 참조
b.i=99;
System.out.println(a.i); //<<<99
//메서드 의 call by reference 확인
change(b);
System.out.println(a.i);
System.out.println(b.i);//같은 객체 참조 임으로 결과는 30
}
private static void change(ClassEx1 a) {
a.i =30;
}
-
정적 멤버의 사용 - 클래스
public class ClassEx2Static {
//설계도 자체의 속성과 기능은 static으로 정의한다.
//즉 공통기능의 정의.
static int i;
static Integer j;
static char[] charArr;
static String str;
static void method() {
//static 메서드에서 인스턴스 멤버에는 접근 불가함
}
void method2() {
}
}
-
정적 멤버의 사용- 메인 메서드
public class MainEx2 {
public static void main(String[] args) {
//공통 기능임으로 클래스명으로 바로 접근 가능
System.out.println(ClassEx2Static.i);
System.out.println(ClassEx2Static.j);
System.out.println(ClassEx2Static.charArr);
System.out.println(ClassEx2Static.str);
/////
ClassEx2Static.method();
}
}
Call by Value 와도 엮여 있는 상태이고, static과 instance 멤버의 차이를 이해하는게 코드설계에서 이점이 많다.
'JAVA-Basic' 카테고리의 다른 글
6.Interface와 다형성의 구현과정 (0) | 2020.07.10 |
---|---|
5.추상클래스와 상속관계의 Promotion & Casting (0) | 2020.07.10 |
4.상속(Inheritance)과 다형성의 구현과정 (0) | 2020.07.10 |
3.Overloading 과 접근제한(AccessModifier) (0) | 2020.07.10 |
1. 원시타입 변수와 참조타입 변수의 할당 원리 (0) | 2020.07.10 |