문제

- 메인함수 실행시 data1, data2, data3의 id값이 1씩 들어가고 있다.

- 메인함수에서 Data클래스의 인스턴스를 생성시 Id값이 1씩 증가하여 값이 들어가게 하고 싶음
- static 키워드를 사용하여 아래의 출력 예시처럼 나오도록 수정해주세요

 

출력 예시

data1.Id = 1
data2.Id = 2
data3.Id = 3

 

// Main클래스

package ex2.quiz;

public class Main {
    public static void main(String[] args) {
        Data data1 = new Data("A");
        System.out.println("data1.Id = " + data1.Id); // data1.Id = 1

        Data data2 = new Data("B");
        System.out.println("data2.Id = " + data2.Id); // data2.Id = 1

        Data data3 = new Data("C");
        System.out.println("data3.Id = " + data3.Id); // data3.Id = 1

    }
}

 

// Data 클래스

package ex2.quiz;

public class Data {
    public String name;
    public int Id;

    public Data(String name) {
        this.name = name;
        this.Id++;
    }
}

 

'자바 문제 > 실습' 카테고리의 다른 글

제네릭 실습 문제  (0) 2024.07.30
다형성 실습 문제  (0) 2024.07.24
상속 실습 문제  (0) 2024.07.22
static 2  (0) 2024.07.17
접근제어자  (0) 2024.07.10

문제1)

다음 중 접근제어자에 대한 설명으로 올바르지 않은 것은 무엇입니까?(중복허용)

 

1. 멤버변수 선언시 접근 제어자는 여러 개 사용 가능하다.

2. 메서드 선언시 접근 제어자를 생략하면 자동으로 public으로 지정된다.

3. default 접근제어자는 모든 패키지의 클래스에서 접근 가능하다.

4. 클래스 내부에 선언된 멤버변수와 메서드를 외부로 부터 보호하기 위해 사용한다.

 

정답) 

1, 2, 3

 

 

문제2)

private와 public에 접근 범위를 작성하시오

 

정답)

private : 같은 클래스 내에서만 접근 가능
public : 모든 곳에서 접근 가능

 


문제3)

캡슐화란 무엇인지 작성하시오

 

정답)

A객체 내부의 속성이나 기능을 하나의 캡슐로 만들어 B객체에서 직접 접근할 수 없게 하는 것이다.

'자바 문제 > 이론' 카테고리의 다른 글

제네릭 이론 문제1  (0) 2024.07.31
추상클래스 이론 문제  (0) 2024.07.24
instanceof 이론 문제  (0) 2024.07.23
상속 이론 문제  (0) 2024.07.17
static  (0) 2024.07.15

문제

- Customer 객체는 자신의 멤버변수와 멤버메서드에만 접근해야한다.
- requestAccountOpening메서드 이외에는 Customer객체는 Bank클래스 내부의 기능을 사용하거나 속성값을 변경할 수 없다.
- 아래 출력 예시와 같이 나오도록 Main클래스와 Bank클래스의 코드를 수정하세요.

 

출력 예시

customer.bankName : 국민은행
customer.balance : 10
customer.accountNumber : 100020003000

 

// Main 클래스

package access.quiz;

public class Main {
    public static void main(String[] args) {

        // 요청사항 확인후 불가능한 코드는 삭제하세요.
        Customer customer = new Customer("kjs");
        customer.bankName = "신한은행";
        customer.balance = 111110;
        customer.accountNumber = 1002132444;
        customer.bankOpenTime = 5;
        customer.bankCloseTime = 20;
        customer.isOpen();
        customer.makeAccountNumber();
        customer.checkAccountType("적금");
        customer.requestAccountOpening(10, "국민은행", "적금");


        System.out.println("customer.bankName : " + customer.bankName);
        System.out.println("customer.balance : " + customer.balance);
        System.out.println("customer.accountNumber : " + customer.accountNumber);

    }
}

 

// Customer

package access.quiz;

public class Customer extends Bank {

    public String name;

    public Customer(String name) {
        //super();
        this.name = name;
    }

    public void requestAccountOpening(int balance, String bankName, String accountType) {
        super.createAccount(balance, bankName, accountType);
        System.out.println("계좌 개설 완료되었습니다.");
    }
}

 

// Bank 클래스

package access.quiz;

public class Bank {

    public int balance;
    public String bankName;
    public int accountNumber;
    public int bankOpenTime = 9;
    public int bankCloseTime = 16;


    // 계좌 개설
    public void createAccount(int balance, String bankName, String accountType) {
        isOpen();
        checkAccountType(accountType);
        setBankName(bankName);
        makeAccountNumber();
    }

    // 영업시간 여부 확인
    public boolean isOpen() {
        int nowTime = 10;
        return bankOpenTime < nowTime && bankCloseTime > nowTime ? true : false;
    }

    // 계좌 종류 확인
    public void checkAccountType(String type) {
    }

    // 계좌번호 생성
    public void makeAccountNumber() {
    }

    // 은행명 설정
    public void setBankName(String bankName) {
    }


}

 

'자바 문제 > 실습' 카테고리의 다른 글

제네릭 실습 문제  (0) 2024.07.30
다형성 실습 문제  (0) 2024.07.24
상속 실습 문제  (0) 2024.07.22
static 2  (0) 2024.07.17
static 1  (0) 2024.07.15

this

  - 자신의 인스턴스에 접근할때 사용

  - 보통 this.을 사용하여 멤버 변수에 접근함

  - 메서드, 생성자에서 사용하는 매개변수(파라미터)이름과 해당 클래스 멤버 변수명이 같을때 구분하기 위해 사용

public class Student {
    public String name;
    public String grade;

    public Student(String name, String grade) {
        this.name = name;
        this.grade = grade;
    }
}

생성자(constructor)

  - 생성자의 목적은 객체 초기화 이다.

  - 생성자의 이름은 클래스 이름과 같아야 한다.

  - 생성자는 반환 타입이 없다.

  - 생성자는 인스턴스를 생성한 후 바로 호출된다.(객체당 한번만 호출)

  - 개발자가 생성자를 작성하지 않으면 컴파일러가 자동으로 기본 생성자 삽입

  - 생성자는 오버로딩 가능하다

 

생성자 장점

  - 직접 정의한 생성자를 호출 하지 않을경우 컴파일 오류가 발생하기 때문에 필수값 입력을 보장할 수 있다.

 

this()

  - 생성자 내부에서만 사용할 수 있다.

  - 생성자의 첫 줄에서만 this()를 사용할 수 있다.

 

public class Student {
    public String name;
    public String grade;


    Student(String name, String grade) {
        this.name = name;
        this.grade = grade;
    }

    Student(String name) {
        this(name, "A");
    }
}

public class Main {
    public static void main(String[] args) {
        // Student student0 = new Student(); // error : no suitable constructor found for Student(no arguments)
        Student student1 = new Student("Kim");
        Student student2 = new Student("Kim", "C");

        Student[] students = {student1, student2};

        for (Student student : students) {
            System.out.println("student.name = " + student.name);
            System.out.println("student.grade = " + student.grade);
        }

    }
}

'인강 > 자바(기본편)' 카테고리의 다른 글

다형성  (0) 2024.07.23
상속  (0) 2024.07.22
변수와 초기화  (0) 2024.07.02
기본형 vs 참조형  (0) 2024.07.01
클래스와 데이터  (0) 2024.07.01

변수의 종류

멤버 변수 : 클래스 내부에서 선언

지역 변수 : 메서드 내부에서 선언, 매개변수도 지역 변수의 한 종류

 

변수의 값 초기화

- 멤버 변수(자동 초기화)

  - 개발자가 초기값을 지정할 수 있음

  - 초기값을 지정하지 않았을 경우

    - int -> 0

    - boolean -> false

    - 참조형 -> null

// 멤버 변수 초기화

class Test {
    int num;
    String str;
    boolean check;
    String[] strArr = new String[5];

    int[] numArr = new int[5];
}

public class Main {
    public static void main(String[] args) {
        Test test = new Test();
        System.out.println("test.num = " + test.num);  // 0
        System.out.println("test.str = " + test.str); // null
        System.out.println("test.check = " + test.check); // false
        System.out.println("test.check = " + test.strArr[0]); // null
        System.out.println("test.check = " + test.strArr[3]); // null
        System.out.println("test.check = " + test.numArr[0]); // 0
        System.out.println("test.check = " + test.numArr[3]); // 0
    }
}

 

- 지역 변수(수동 초기화)

  - 항상 직접 초기화해야 한다.

// 지역변수 초기화 안했을 경우

int num;
String str;
boolean check;
String[] strArr = new String[5];
int[] numArr = new int[5];

System.out.println("num = " + num); // error : variable num might not have been initialized
System.out.println("str = " + str);  // error : variable str might not have been initialized
System.out.println("check = " + check); // error : variable check might not have been initialized
System.out.println("check = " + strArr[0]); // null
System.out.println("check = " + strArr[3]); // null
System.out.println("check = " + numArr[0]); // 0
System.out.println("check = " + numArr[3]); // 0

 

 

'인강 > 자바(기본편)' 카테고리의 다른 글

다형성  (0) 2024.07.23
상속  (0) 2024.07.22
this, 생성자  (0) 2024.07.02
기본형 vs 참조형  (0) 2024.07.01
클래스와 데이터  (0) 2024.07.01

기본형(primitive type)

  - 정수타입 : byte, short, int, long

  - 실수타입 : float, double

  - 문자타입 : char

  - 논리타입 : boolean

 

참조형(reference type)

  - 배열 타입

  - 열거 타입

  - 클래스

  - 인터페이스

  - 기본형을 제외한 나머지

 

기본형 vs 참조형 - 변수 대입

대원칙 : 자바는 항상 변수의 값을 복사해서 대입한다.

- 기본형 : 변수에 들어 있는 실제 사용하는 값을 복사해서 대입

- 참조형 : 변수에 들어 있는 참조값을 복사해서 대입

// 기본형 변수 대입
int a = 10;
int b = a;

System.out.println("a = " + a); // 10
System.out.println("b = " + b); // 10

b = 20;

System.out.println("a = " + a); // 10
System.out.println("b = " + b); // 20



// 참조형 변수 대입
Student student1 = new Student();
student1.name = "kim";
Student student2 = student1;

System.out.println("student1.name = " + student1.name); // kim
System.out.println("student2.name = " + student2.name); // kim

student2.name = "Lee";

System.out.println("student1.name = " + student1.name); // Lee
System.out.println("student2.name = " + student2.name); // Lee

 

 

기본형 vs 참조형 - 메서드 호출

대원칙 : 자바는 항상 변수의 값을 복사해서 대입한다.

- 기본형 : 메서드로 기본형 데이터를 전달하면 해당 값이 복사되어 전달됌.

- 참조형 : 메서드로 참조형 데이터를 전달하면 참조값이 복사되어 전달됌.

// 기본형 메서드 호출
public static void main(String[] args) {
    int a = 10;
    System.out.println("a = " + a); // 10
    changePrimitive(a);
    System.out.println("a = " + a); // 10

}

static void changePrimitive(int x) {
    x = 20;
}

// 참조형 메서드 호출
public static void main(String[] args) {
    Student student = new Student();
    student.name = "kim";
    System.out.println("student.name = " + student.name); // kim
    changeReference(student);
    System.out.println("student.name = " + student.name); // Lee

}

static void changeReference(Student data) {
    data.name = "Lee";
}

 

'인강 > 자바(기본편)' 카테고리의 다른 글

다형성  (0) 2024.07.23
상속  (0) 2024.07.22
this, 생성자  (0) 2024.07.02
변수와 초기화  (0) 2024.07.02
클래스와 데이터  (0) 2024.07.01

클래스(class)

- 클래스에 정의한 변수들을 멤버 변수, 필드라고 한다.

  - 멤버 변수(Member Variable) : 클래스 영역에서 선언된 변수

  - 필드(Field) : 데이터 항목을 가리키는 용어(데이터베이스, 엑셀 등에서 각각의 항목을 지칭)

public class Student {
    String name; // 멤버 변수, 필드
    String grade; // 멤버 변수, 필드
}

 

인스턴스 생성

Student student; // 1. 변수 선언
student = new Student(); // 2. 인스턴스 생성
student = x001 // 3. 참조값 보관및 반환

객체(Object) : 클래스에서 정의한 속성과 기능을 가진 실체

인스턴스(Instance) : 특정 클래스로부터 생성된 객체를 의미함

'인강 > 자바(기본편)' 카테고리의 다른 글

다형성  (0) 2024.07.23
상속  (0) 2024.07.22
this, 생성자  (0) 2024.07.02
변수와 초기화  (0) 2024.07.02
기본형 vs 참조형  (0) 2024.07.01

String 클래스를 통해 문자열 생성 방법

- String 클래스는 기본형이 아니라 참조형이다.

- 문자열은 매우 자주 사용되어 자바 언어에서는 아래 1번과 같이 작성해도 new String("hello")와 같이 변경해준다.

1. String str1 = "hello";
2. String str1 = new String("hello");

 

String 클래스 - 비교

동일성(Identity) : == 연산자를 사용해서 두 객체의 참조가 동일한지 확인

동등성(Equality) : equals() 메서드를 사용하여 두 객체가 논리적으로 같은지 확인

String str1 = "hello";
String str2 = new String("hello");
String str3 = new String("hello");

System.out.println(str1 == str2); // false
System.out.println(str2 == str3); // false
System.out.println(str1.equals(str2)); // true
System.out.println(str2.equals(str3)); // true

 

문자열 풀

- String str = "hello"와 같이 문자열  리터럴을 사용하는 경우 자바는 메모리 효율성과 최적화를 위해 풀을 사용한다.

- 자바가 실행되는 시점에 문자열 리터럴이 있으면 문자열 풀에 String 인스턴스를 만들어둔다.

- 같은 문자열이 있으면 String 인스턴스를 만들지 않고 동일한 문자열에 인스턴스를 찾고 해당 인스턴스를 참조한다.

String str1 = "hello";
String str2 = "hello";

System.out.println(str1 == str2); // true
System.out.println(str1.equals(str2)); // true

불변 객체

1. 변경이 필요한 경우 기존 값을 변경하지 않고 새로운 결과를 만들어서 반환한다.

2. String 내부의 값을 변경할 수 있다면 기존에 문자열 풀을 통해 같은 문자를 참조하는 변수의 String값이 변경되는 문제가 생길 수 있음

// 1번 예제
String str1 = "hello";
str1.concat("java");
String str2 = str1.concat(" java");

System.out.println("str1 = " + str1); // hello
System.out.println("str2 = " + str2); // hello java

// 2번 예제
String str3 = "hello";
String str4 = "hello";
str2 = "bye";

System.out.println("str3 = " + str3); // hello
System.out.println("str4 = " + str4); // bye

 

StringBuilder 가변 String

- 내부의 값을 변경할 수 있는 String

- 변경된 값을 사용할때 불변 객체와 다르게 새로운 객체를 생성하지 않는다.

- 내부의 값을 변경할때마다 새로운 객체를 생성하는게 아니기 때문에 성능과 메모리 측면에서 효율적이다.

불변 객체 값 변경

// 문자열 변경시 동작 순서
String str = String("A") + String("B") + String("C") + String("D");

// 1
String str = new String("AB") + String("C") + String("D");

// 2
String str = new String("ABC") + String("D");

// 3
String str = new String("ABCD");

- 1번과 2번에서 생성된 new String("AB")과 new String("ABC")은 사용되지 않는다.
- 이후에 GC의 대상이 된다.

가변 객체 값 변경

 StringBuilder sb = new StringBuilder();
 
 sb.append("A");
 sb.append("B");
 sb.append("C");
 sb.append("D");
 
 System.out.println("sb = " + sb); // ABCD

 

'인강 > 자바(중급1편)' 카테고리의 다른 글

불변 객체  (0) 2024.05.06
Object 클래스  (0) 2024.04.23

+ Recent posts