백지부터 시작하는 이세계 코딩 생활
instance 와 this 본문
instance 미국∙영국 [ɪnstəns] : 함수 사용하기 전에 선언(호출)하는 것 => Class의 생서자를 호출하는 것.
1. You use for instance to introduce a particular event, situation, or person that is an example of what you are talking about.
2.구 You say in the first instance to mention something that is the first step in a series of actions.
3.명사 An instance is a particular example or occurrence of something.
Collins Cobuild Advanced Learner's English Dictionary
package s0511;
public class Ch13Ex00 {
public static void main(String[] args) { //접근지정자 public이 없다면 같은 클래스 내에서만 사용가능함.
// TODOAuto-generated method stub
}//end main
}//end class
// 포인트 연산자 : 객체접근 가능하게 해줌.
// *** 자신의 인스턴스를 지칭하는 this
// 객체가 매서드를 호출했을 때, 참고하고 있는 값이 this로 지칭되고 사용됨.
// 각각의 객체에서 이름이 같은 변수를 this를 통해 그때그때 불러서 사용하게 됨.
// pt01 을 호출하면 pt01의 x가 사용되고, pt02를 호출하면 pt02의 x값이 사용됨.
// public void setX(int x){ this.x = x; }
// 멤버필드와 매개변수 구분에 유의. : 표시는 this.x = x; 와 같이 사용하면 됨.
// this가 붙은 쪽이 멤버필드, 없는쪽이 매개변수.
// *** 생성자에서 호출할 때 this 를 사용하면 됨.
// cf. Super.x(멤버) 처럼 쓰면 상위클래스를 호출 할 수 있음. (부모클래스)
// <import와 패키지 >
// "폴더" 개념이다. import와 패키지는,
// project 관리의 편의성을 위해 사용함.
// cf. 서버관리는 리눅스가 99%
// 패키지를 만들었을 때, 도메인은 반대로 만들어준다.(약속임), 클래스간의 충돌을 방지할 수 있음.
// 패키지가 다르면 import 해줘야함
// mvnrepository.com 공식적인 라이브러리 검색을 할 수 있음.
// java의 모든 클래스를 import할 때 : import java.lang.*;
// 다른 하위 패키지는 불러와지지 않음. 따로 불러와야함.
// <컬렉션 클래스와 제네릭>
// set은 중복을 허용하지 않는다. (자동 중복처리를 필터링해줌)
// Iterator 인터페이스
// JAVA : DB와 Collection이 절반임. 없는 함수는 직접 만들어야 하지만.
// <ArrayList>
// 중복없이 나열가능하다.
//
// <VectorList>
//
package s0511;
class Point{
int x, y; //생성자
public Point() {
this(0, 0); // 생서자 호출이 오기 전 다른 문장이 오면 에러남. *주의*
System.out.println("포인트 클래스의 default 생성자");
}//end
public Point(int x) {
// this.x = x;
this(x, 0); // 생성자 호출 방법
}//end
public Point(int x, int y) {
this.x = x;
this.y = y;
}//end
public void showPoint() {
System.out.println(x+","+y);
}//end
}//end class
public class Ch13Ex01 {
public static void main(String[] args) {
Point p1 = new Point();
Point p2 = new Point(10);
Point p3 = new Point(199, 1);
p1.showPoint();
p2.showPoint();
p3.showPoint();
}//end
}//end class
// ** 중요사항 ** //
// this 는 인스턴스와 관련되어있음. 객체를 통해서 접근가능함. (변수 만들어 쓰는것이 이에 해당함)
// static 은 클래스 멤버와 관련있음. 클래스 이름을 통해 접근가능함.
// static 이 없는 모든 멤버는 인스턴스 멤버에 해당함.
// *** static 맴버는 인스턴스에 접근 할 수 없음.
// 그래서 static 멤버는 static 멤버끼리만 접근 가능하다.
// 그러나 인스턴스 멤버는 static 멤버에 접근가능하다.
// ** 적용되는 범위가 다르다는 것에 유의하자. **
// static이 붙으면 class 레벨임(차원임)
// <정적메소드 사용시 유의할 점>
// static 매소드에서는 this 래퍼런스를 사용불가.
// 정적 메소드에서는 인스턴스 변수 사용불가.
//
//
<결과확인>
package s0511;
class Account {
int money;
static int total;
public Account(int money) { // 생성자 만듬.
this.money = money;
total += money;
}//end
public static void showTotal() { //인스턴스가 공통으로 사용할 수 있도록 접근허락.
System.out.println("total: "+total);
}//end
public void showMoney() {
System.out.println("money: "+money);
}//end
}//
public class Ch13Ex02 {
public static void main(String[] args) {
Account acc01 = new Account(199); // 생성과 값 대입. 괄호속 값이 변수값이고 여기서는 money값에 해당함.
Account acc02 = new Account(1);
Account acc03 = new Account(200);
acc01.showMoney();
acc02.showMoney();
acc03.showMoney();
System.out.println();
acc01.showTotal();
acc02.showTotal();
acc03.showTotal(); //값이 쌓여감.?
}// end main
}// end class
<결과확인>
package s0511;
class People{
private static int sequence = 1;
private int number;
private String name;
public People(String name) {
this.name = name;
number = sequence++;
}//end
public static void showSequence() { //인스턴스가 공통으로 사용할 수 있도록 접근허락.
System.out.println("sequence:=> "+sequence);
}//end
@Override // <= 문자를 붙여주면 오류를 확인할 수 있음.
//toString 같은 경우 자동호출 되는 매소드이다. Object(객체)에 있기 때문.
public String toString() {
return "People [number=" + number + ", name=" + name + "]";
}
}//
public class Ch13Ex03 {
public static void main(String[] args) {
People p1 = new People("H");
People p2 = new People("K");
People p3 = new People("L");
System.out.println(p1); // (number = 1, name = H) 와 같이 출력
System.out.println(p2); // (number = 2, name = K) 와 같이 출력
System.out.println(p3); // (number = 3, name = L) 와 같이 출력
People.showSequence(); // sequence => 4 나올 수 있게 프린트.
//tip 생성자와 to.String 사용.
}//end
}//
<결과확인>
package s0511;
import java.util.ArrayList;
public class Ch13Ex07_Exmaple_1_ArrayList { //ArrayList 예제
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
// 제네릭
// ArrayList에는 타입관계없이 다 담을 수 있음.
// 위 예제는 타입제한을 준것임. 때로는 타입 지정이 더 안전하고 편리할 수 있음.
list.add("A");
list.add("B");
list.add("O");
list.add("Or");
list.add("B");
System.out.println("size: " + list.size());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("print1\t");
// 확장 for문 사용가능함.
for (String item : list) {
System.out.println(item);
}
System.out.println("print2\t");
// 리스트를 배열로 변환
String[] strArr = new String[list.size()];
list.toArray(strArr);
for (int i = 0; i < strArr.length; i++) {
System.out.print("print3:"+strArr[i] + "\n");
}
}// end main
}//
package s0511;
import java.util.ArrayList;
import java.util.Scanner;
public class Ch13Ex08_Exmaple_2_ArrayList {
static int Select() {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
return i;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("W");
list.add("M");
list.add("S");
list.add("W");
list.set(2, "K");
list.remove(3);
// 리스트를 배열로 변환
String[] stringArray = new String[list.size()];
//문자열 타입의 배열 선언.
list.toArray(stringArray); // 리스트를 배열로 변환.
for (int i = 0; i < stringArray.length; i++) { //크기 자동 조정.
System.out.print(stringArray[i] + "\t");
//배열 형태로 프린트.
}
System.out.println();
// 변경 후.
// System.out.println("1: 삽입\t 2: 변경\t 3: 삭제");
// for (int i = 0; i < stringArray.length; i++) { //크기 자동 조정.
// System.out.print(stringArray[i] + "\t");
// }
// System.out.println("--------------------------");
//
// switch (Select()) {
// case 1: //list.add
// System.out.println("삽입선택");
// list.add(2, "K");
// for (int i = 0; i < stringArray.length; i++) {
// System.out.print(stringArray[i] + "\t");
// }
// break;
// case 2:
// System.out.println("변경선택");
// list.set(3, "P");
// for (int i = 0; i < stringArray.length; i++) {
// System.out.print(stringArray[i] + "\t");
// }
// break;
// case 3:
// System.out.println("삭제선택");
// list.remove(3);
// for (int i = 0; i < stringArray.length; i++) {
// System.out.print(stringArray[i] + "\t");
// }
// break;
// default:
//
// }
}// end
}//
//ArrayList 에서 원소 추가,변경,삭제 연습
//책 연습문제
<결과확인>
package s0511_4;
import java.util.Random;
import java.util.HashSet;
public class TestLotto {
public static void main(String[] args) {
// HashSet으로 로또코드 만들기.
HashSet lotto = new HashSet();
Random rd = new Random();
while (lotto.size() < 6) {
lotto.add(1 + rd.nextInt(45));
//발생한 개수가 10개보다 작으면 자동정렬이 된다.
}
//배열속 값들 정렬하기.
// Collections.sort
System.out.println(lotto);
}// end
}//
<결과확인>
package s0511_4;
import java.util.HashSet;
import java.util.Iterator;
public class TestSet {
public static void main(String[] args) {
//Set 구조의 객체 생성
HashSet set = new HashSet();
// HashSet 특징 : 중복값을 입력할 수 없다.
set.add("K");
set.add("K1");
set.add("K2");
set.add("KK");
set.add("K");
set.add("K1");
System.out.println(set.size()); //중복체크, 중복되지 않은 갯수들을 확인.
Iterator elements = set.iterator();
while(elements.hasNext()) { //자동으로 요소체크. index 자동 이동.
System.out.println(elements.next());
}
}//end
}//
<결과확인>
'JAVA > etc' 카테고리의 다른 글
vc code with spring (0) | 2020.08.23 |
---|---|
Tomcat port 중복될 때 (0) | 2020.08.20 |
#객체와 클래스 #접근지정자 #사각형넓이 구하기 (0) | 2020.08.09 |
enum 함수 (0) | 2020.08.09 |
반복문 들어가기 전에.. (0) | 2020.08.08 |
Comments