학원 16일차 - Java

44246 단어 학원자바자바

2021.04.19

숫자 3글자마다 ,찍는 방법

  • printf("형식문자열", 인자) : 출력
  • String.format("형식문자열", 인자) : 반환
String.format("가격 : %,d원", price)

Getter, Setter 자동생성

  • Getter, Setter -> 누가 만들어도 동일한 코드
  • 자주 반복되는 코드 -> Boilerplate Code -> 생산성 문제.. -> 어떻게 자동화? -> 발전중..!!
  1. 이클립스 기능

    a. context Menu -> Source

    b. Code Template(syso, main, reder,,) or Code Snppet (코드 조각

  1. 외부 기능- Lombok(롬복)
    • Lombok(롬복) Library -> 설치(설정)

  1. 이클립스 - package Explorer - 새로운 폴더 생성 - lombok.jar복사해서 폴더에 넣기
  2. 우측버튼 - Build Path - Configure Build Path -Libraries jar파일 가져오기(Lombok설치)

  1. Getter & Setter을 만들 변수가 있는 클래스 파일에서 import하기

    어노테이션(Annotation)

    @Setter -> ctrl + space

    @Getter -> ctrl + space

    @Data -> ctrl + space

import lombok.Data;
import lombok.Getter;
import lombok.Setter;


//@xxx : 어노테이션(Annotation) -> 주석같은 형태 + 프로그래밍 언어
@Getter
@Setter

@Data //@Getter, @Setter,, @toString()...기본 모음

public class Glass {

    //Lombok기능을 사용하면 -> 메서드 편집 불가능 -> 유효성검사, 데이터 조작 -> 개발자 개입 불가능 -> 그럼 언제 사용? 
    //멤버변수를 (private) + Getter/Setter 으로 사용하는 이유
    // -> 잘못된 데이터가 유입될까봐 -> 유효성 검사

    //객체를 사용하는 환경
    //1. 열린 환경
    // - 내가 만든 클래스를 소통이 없는 다른 사람이 사용할 수 있는 환경

    //2. 닫힌 환경
    // - 내가 만들 클래스를 나만 사용하거나, 의사 소통이 아주 긴밀한 사람들만이 사용할 수 있는 환경
    // - 유효성 검사가 필요 없는 클래스 멤버


    private String name;
    private String color;
    private int pirce;

}
  1. 객체 사용
public class Ex35_Class {

    public static void main(String[] args) {

        Glass g1 = new Glass();

        g1.setColor("노랑");

        System.out.println(g1.getColor());


    }
}

참조형 배열

  • 값형(원시형) 배열
int[] num = new int[3];  //int x 3
num[0] = 10;
num[1] = 20;
num[2] = 30;

//출력
for(int n : num) {
    System.out.println(n);
}
  • 참조형 배열
public class Ex36_Class {

    public static void main(String[] args) {


        Item item1 = null; //참조변수에 주소가 들어있지 않음. 
        Item item2 = new Item(); //참조변수에 객체 주소가 들어있음.
        Item item3;	

        //초기화하지 않은 지역변수는 사용이 불가능하다.
        //java.lang.NullPointerException or NullReferenceException or 널참조에러 => 참조변수는 있지만 객체가 없어서 나는 에러
        //item1.setColor("노랑"); -> 에러
        //System.out.println(item1.getColor()); -> 에러


        //Item 방을 만들려면
        // -> Item item

        //Item 객체(붕어빵)을 만들려면
        // -> new Item()

        Item[] items = new Item[3]; //Item x 3

        //객체를 생성해서 배열의 각 요소에 저장★★★
        items[0] = new Item(); //Item item1 = new Item(); 동일
        items[1] = new Item();
        items[2] = new Item();

        //java.lang.NullPointerException
        // - 예외 중에 발생 1위
        items[0].setName("키보드");
        items[0].setColor("검정");
        items[0].setPrice(50000);

        System.out.println(items[0].getName());
        System.out.println(items[0].getColor());
        System.out.println(items[0].getPrice());

    }//main

}//Ex36


class Item {

    private String name;
    private String color;
    private int price;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }

}


static 키워드

  • 클래스 멤버에게 붙이는 키워드

멤버 변수

  1. 멤버 변수
  • 객체 멤버 변수

    • 각 객체가 (개인이) 각각의 자신만의 값을 가져야 하는 경우에 사용한다.
  • 정적 멤버 변수(Static 멤버 변수)

    • 객체가 속한 클래스의 모든 객체가 동일한 값(공용된 값)을 가져야 하는 경우에 사용한다.
  1. 멤버 메소드
  • 객체 멤버 메소드
    • 객체가(개인이) 하는 행동을 구현하는 경우(-> 개인의 데이터를 사용해서 횅동한다.)
  • 정적 멤버 메소드
    • 객체가 하는 행동이 개인의 행동이 아닌 전체를 대변하는 행동을 구현하는 경우.

★★★★★★

  1. 개인 정보 -> 객체 변수 저장 -> 객체 메소드로 행동
  2. 공용 정보 -> 정적 변수 저장 -> 정적 메소드로 행동(static)
public class Ex37_Static {

    //클래스 로딩 -> static 할당(static멤버를 인식) -> main()실행
    public static void main(String[] args) {

        // static int a = 10; //지역변수 x

        Student.setSchool("역삼 중학교"); //정적 멤버 변수


        Student s1 = new Student();

        s1.setName("홍길동");
        s1.setAge(15);
        //s1.setSchool("역삼 중학교");


        Student s2 = new Student();

        s2.setName("아무개");
        s2.setAge(14);
        //s2.setSchool("역삼 중학교");



        Student s3 = new Student();

        s3.setName("토마토");
        s3.setAge(16);
        //s3.setSchool("역삼 중학교");



        //학생 1명 -> 질문
        //A. 홍길동이 다니는 학교가 어디니?
        //B. 홍길동과 같은 학생들이 다니는 학교가 어디니?

        System.out.println("이름 : " + s1.getName()); //개인정보
        System.out.println("나이 : " + s1.getAge()); //개인정보
        //System.out.println("학교 : " + s1.getSchool());  //A. 개인정보  -> ★★★ 다른 사람과 다른 값을 가질 수 있다.
        System.out.println("학교 : " + Student.getSchool()); //B. 공용정보 -> 모든 사람이 항상 같은 값을 가진다. 

        System.out.println();

        System.out.println("이름 : " + s2.getName());
        System.out.println("나이 : " + s2.getAge());
        System.out.println("학교 : " + Student.getSchool());

    }//main

}


class Test {

    public int a;
    public static int b; //멤버변수 O

    public void aaa() {
        
    }

    public static void bbb() {
        
    }
}


//학생클래스
// 학생들은 모두 -> "역삼 중학교"   
class Student {

    private String name;
    private int age;

    //private String school;
    private static String school; //static 사용 -> 공통정보라서
    

    public static String getSchool() {
        return school;
    }
    public static void setSchool(String school) {
        Student.school = school;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

 //	public String getSchool() {
 //		return school;
 //	}
 //	public void setSchool(String school) {
 //		this.school = school;
 //	}

}

public class Ex38_Static {

	public static void main(String[] args) {
		
		// 목적) 생산한 마우스의 갯수 세기
		
		//Case A.
//		int count = 0; //누적 변수
//		
//		Mouse m1 = new Mouse(); //생산
//		count++; //카운팅
//		
//		Mouse m2 = new Mouse();
//		count++;
//		
//		Mouse m3 = new Mouse();
//		count++;
//		
//		System.out.printf("총 갯수: %d개\n", count);
		
		
		
		
		//Case B.
//		Mouse m1 = new Mouse();
//		
//		//m1.setCount(m1.getCount() + 1); //private으로 했을 경우
//		m1.count += 1;
//		
//	
//		Mouse m2 = new Mouse();
//		//m2.count += 1;
//		m1.count += 1;
//		
//		Mouse m3 = new Mouse();
//		//m3.count += 1;
//		m1.count += 1;
//		
//		System.out.printf("총 갯수: %d개\n", m1.count);
//		
		
		
		//Case C.
		Mouse m1 = new Mouse();
		Mouse.count++;
		
		Mouse m2 = new Mouse();
		Mouse.count++;
		
		Mouse m3 = new Mouse();
		Mouse.count++;
		
		System.out.printf("총 갯수: %d개\n", Mouse.count);

	}

}

class Mouse {
	
	private String model; //개인 정보(객체)
	
	public static int count; //공용 정보(정적)
	
	//public int count; //누적변수

//	public int getCount() {
//		return count;
//	}
//
//	public void setCount(int count) {
//		this.count = count;
//	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}
}

멤버

  1. 변수

    a. 객체 변수 -> 개인 정보 저장

    b. 정적 변수 -> 공용 정보 저장

  1. 메소드

    a. 객체 메소드 -> 개인 행동

    • 객체 변수 접근 가능
    • 정적 변수 접근 가능

    b. 정적 메소드 -> 공용(단체) 행동

    • 객체 변수 접근 불가능 (개인 정보 사용 불가.)
    • 정적 변수 접근 가능
public class Ex39_Static {

	public static void main(String[] args) {
		
		//외부 환경
		//1. 객체 변수 접근
		StaticItem item1 = new StaticItem();
		//1. 객체 변수 접근
		item1.a = 100;
		
		//2.정적 변수 접근
		StaticItem.b = 200;
		
		item1.aaa();
		StaticItem.bbb();
		
	}//main
	
}//Ex39


class StaticItem{
    
	public int a = 10;
	public static int b = 20;
	
	
	//객체 메소드
	public void aaa() {
		System.out.println(a);
		System.out.println(b);
		
		System.out.println(this.a); //this - 같은 객체 내부라서 생략 가능 
		System.out.println(StaticItem.b); //StaticItem - 같은 클래스 내부라서 생략 가능
		
	}
	
	//정적 메소드
	public static void bbb() {
		//System.out.println(this.a); //Cannot make a static reference to the non-static field a
		System.out.println(StaticItem.b);
				
	}
}

좋은 웹페이지 즐겨찾기