공부일지

231006 (Java)

CD가참둥그렇다 2023. 10. 6. 17:31

클래스와 객체

  • 객체 : 물리적으로 존재하거나 추상적으로 생각할 수 있는 것 중에서 자신의 속성을 가지며 식별 가능한 것
  • 객체는 속성과 동작으로 구성됨
    • 속성(필드) - 변수와 유사
    • 동작(메소드) - 메소드와 유사
  • 클래스 = 자바의 설계도
  • 인스턴스 = 클래스로부터 만들어진 객체. class를 직접 가져온 경우 설계도이기 때문에 작동하지 않음.
  • 인스턴스를 동작하도록 하려면 new를 사용한다.
  • static = 항상 메모리에 올라간 상태. new를 사용하지 않더라도 객체를 불러올 수 있다.
    • 항상 메모리에 올라가 있기 때문에 메모리의 낭비가 발생한다.

학생 클래스

  • main : 만든 클래스가 자바 프로그램의 시작점인 경우에 사용한다.
  • 클래스를 외부에서 사용하기 위한 방법
  • 클래스 내부에 다른 클래스의 삽입 가능. 클래스 이름 뒤에 Main을 붙이는 경우 자바 프로그램의 시작점을 가지는 클래스로 바로 확인 가능
  • Ex01_Student es = new Ex01_Student();
    • Ex01_Student의 모든 기능을 사용 가능한 상태로 메모리에 올린다.
    • new를 사용하여 인스턴스화 한다.
  • 클래스도 다른 배열이나 String처럼 사용 가능하다.
  • new 클래스 = 메모리 힙 영역에 객체를 생성해 준다.
package pack01.exclass;

public class Ex01_StudentMain {
	public static void main(String[] args) {
		System.out.println("시작점");
		Ex01_Student es = new Ex01_Student();
		Ex01_Student cd = null;
		
		if (es==cd) {
			System.out.println("o");
		} else {
			System.out.println("x");
		}
	}
}

자동차

  • fied(속성) : 전역변수, 클래스의 멤버 = 중괄호에서 만들어진 것
  • main 내부의 변수들은 main 메소드의 지역 변수.
  • 전역 변수 : 인스턴스화를 통해 메모리에 올라가기 때문에 외부에서 사용이 가능하다.
  • 클래스 내부에서는 어디서든 사용 가능하다.
  • 필드= 인스턴스 멤버= 인스턴스 변수= 속성= 전역변수
  • 클래스 이름 + 변수 이름 = new 클래스 이름();
    • 인스턴스화 식
  • 인스턴스화 된 객체(변수 이름)에 .을 찍으면 하위 객체들이 표시된다.
  • 전역변수는 초기값 없으면 사용이 불가능 하지만 전역변수는 기본값을 가져서 즉시 사용이 가능하다.
public class CarMain {
	public static void main(String[] args) {
		Car carh = new Car();
		Car cark = new Car();
		carh.company = "현대";
		cark.company = "기아";
		System.out.println(carh.company);
		System.out.println(cark.company);
		carh.type = "SUV";
		carh.maxSpeed = 200;
		carh.color = "silver";
		System.out.println(carh.type);
		System.out.println(carh.maxSpeed);
		System.out.println(carh.color);
	}
}

전역 변수의 선언과 호출 테스트

  • 객체를 필요로 하는 변수의 경우 전역변수를 가져오더라도 초기화가 필요하다(ex. 배열)
import java.util.Random;
import java.util.Scanner;

public class TestField {
	boolean typeBoolean;
	byte typeByte;
	short typeShort;
	char typeChar;
	int typeInt;
	long typeLong;
	float typeFloat;
	double typeDouble;
	String typeString;
	
	int[] typeIntArr1;
	int[][] typeIntArr2;
	String[] typeStringArr1;
	String[][] typeStringArr2;
	
	Scanner scan;
	Random ran;
}
import java.util.Random;
import java.util.Scanner;

public class TestFieldMain {
	public static void main(String[] args) {
		TestField call = new TestField();
		
		call.typeBoolean = true;
		call.typeByte = 1;
		call.typeShort = 12;
		call.typeChar = 'A';
		call.typeInt = 1234;
		call.typeLong = 123456789123l;
		call.typeFloat = 1.12f;
		call.typeDouble = 1.11;
		call.typeString = "스트링";
		
		call.typeIntArr1 = new int[3];
		call.typeIntArr2 = new int[3][];
		call.typeStringArr1 = new String[3];
		call.typeStringArr2 = new String[3][];
		
		call.scan = new Scanner(System.in);
		call.ran = new Random(4);
	}
}

메소드

  • new ‘Ex01_Korean()’ : 객체를 생성하기 위한 기능을 가진 메소드
  • 별도의 생성자 메소드를 구현(명시)하지 않으면 기본적으로 클래스의 이름을 메소드로 사용함.
  • 메소드에서 전역변수와 지역변수의 구분
    • this.변수명이 전역변수, 변수명이 지역변수를 나타낸다.
  • 메소드의 () 내부 = 파라미터 부분
public class Ex01_Korean {
	
	String nation = "대한민국";//전역변수, 인스턴스 멤버, 인스턴스 변수, 필드
	String name;//이름
	String ssn;//주민등록번호
	public Ex01_Korean(String ssn, String name) {
		this.ssn = ssn;
		this.name = name;
	}
}
public class Ex01_KoreanMain {
	public static void main(String[] args) {
		Ex01_Korean ko1 = new Ex01_Korean("123456-1234567","박찬영");
		

		System.out.println(ko1.nation);
		System.out.println(ko1.name + ko1.ssn);
		
		String ssn ="123456-1233445";
		Ex01_Korean ko2 = new Ex01_Korean(ssn, "김민주");

		System.out.println(ko2.ssn);
		
	}
}

테스트

  • 내가 사용할 필드를 만들기 (제조사, 모델, 색상, 자동차 이름)
  • 메인에서 각각 필드에 값을 담고 출력하기
  • test_car가 제조사와 자동차 이름이 외부로부터 입력 되었을 때만 생성되게 수정해보기
public class Test01_Car {
	String company;
	String model;
	String color;
	String name;
	
	public Test01_Car(String company, String name) {
		this.company = company;
		this.name = name;
	}

	public Test01_Car(String company, String model, String color, String name) {
		super();
		this.company = company;
		this.model = model;
		this.color = color;
		this.name = name;
	}
	
}
public class Test01_CarMain {
	public static void main(String[] args) {
		Test01_Car car1 = new Test01_Car("benz", "E_class");
		car1.color = "black";
		car1.model = "sedan";
		System.out.println(car1.company);
		System.out.println(car1.name);
		System.out.println(car1.model);
		System.out.println(car1.color);
	}
}