inblog logo
|
MiracleCoding
    JAVA

    [Java] 참조 변수 입니다. (reference variable)

    Dec 21, 2023
    [Java] 참조 변수 입니다. (reference variable)
    Contents
    this 참조 변수
    💡
    참조 변수?
    참조 변수는 객체의 주소를 저장한다. ※참조 변수에 객체가 저장되는 것은 아니다.
    자바에서는 변수를 기초 변수와 참조 변수로 나눌 수 있다. 기초 변수는 int, float, char등의 기초 자료형의 값을 저장하는 변수다.
     

    참조 변수를 활용한 예제

    public class DeskLamp { // 인스턴스 변수 정의 private boolean isOn; // 메소드 정의 public void turnOn() { isOn = true; } public void turnOff() { isOn = false; } public String toString() { return "현재 상태는 " + (isOn == true ? "켜짐" : "꺼짐"); } }
    public class DeskLampTest { public static void main(String[] args) { // 객체를 생성하려면 new 예약어를 사용한다. (heap) DeskLamp myLamp = new DeskLamp(); // 객체의 메소드를 호출하려면 도트 연산자인 .을 사용한다. myLamp.turnOn(); System.out.println(myLamp); myLamp.turnOff(); System.out.println(myLamp); } }
    여기 두 다른 class가 있다. (DeskLamp, DeskLampTest) DeskLamp 클래스의 isOn은 private로 선언됐기 때문에 같은 클래스에서만 사용이 가능하지. 만? 메소드 turnOn(), turnOff() 에 isOne변수의 주소를 저장했기 때문에 DeskLampTest클래스에서 객체를 활용하여 isOn에 접근할 수 있다. (출력만 가능, 입력 X)
    짜잔
    짜잔
     

    자, 두 번째 예제

    class Box{ int width; int length; int height; double getVoume() { return (double) width * height * length; } } public class BoxTest { public static void main(String[] args) { Box b = new Box(); b.width = 20; b.length = 20; b.height = 30; System.out.printf("상자의 가로 : %d, 세로 : %d, 높이 : %d\n", b.width, b.length, b.height); System.out.println("상자의 부피는 " + b.getVoume() + "입니다."); } }
    notion image
     
     
    객체 초기화는 생성자

    this 참조 변수

    ∴this는 (heap)영역 입니다.
    만들기
    Alt + insert → Constructor
    Alt + insert → Constructor
     
    모두 선택
    모두 선택
    notion image
     
    // 설계도 class People { String name; int power; int hp; public People(String name, int power) { this.name = name; this.power = power; this.hp = 100; } } public class PersonEx01 { public static void main(String[] args) { People p1 = new People("티모", 10); } }
    notion image
    notion image
    notion image
     
    Share article

    MiracleCoding

    RSS·Powered by Inblog