Java 시작하기 - 참조 자료형 변수

Big Jay·2023년 8월 28일
0

Java 시작하기

목록 보기
13/14
post-thumbnail

참조 자료형

Java에는 기본 자료형 외에 클래스 자료형으로 선언하는 참조 자료형 변수가 있다.

예제

사람에 대한 정보를 저장하는데 있어 만약, 애완동물에 대한 정보도 입력한다면?

// Person.java
package ReferenceVariable;

public class Person {
	// JDK에서 제공하는 참조 자료형
    String name;
    int age;
    String hobby;
	String petName;
    String species;

    Person(String name, int age, String hobby, String petName, String species){
        this.name = name;
        this.age = age;
        this.hobby = hobby;
		this petName = petName;
		this species; species;  
    }
}

위와 같이 사람의 정보를 저장하는 클래스를 생성하였을 때,
이 때 pet에 대한 정보는 Pet 클래스를 구성할 수 있다.

// Person.java
package ReferenceVariable;

public class Person {
	// JDK에서 제공하는 참조 자료형
    String name;
    int age;
    String hobby;

	// 여기서 Pet은 클래스로 생성한 참조 변수다.
    Pet pet;

    Person(String name, int age, String hobby){
        this.name = name;
        this.age = age;
        this.hobby = hobby;

        pet = new Pet();
    }

    public void setPetName(String name){
        pet.name = name;
    }

    public void setPetspecies(String species){
        pet.species = species;
    }
}
// Pet.java
package ReferenceVariable;

public class Pet {
    String name;
    String species;
}
// User.java
package ReferenceVariable;

public class User {
    public static void main(String[] args){
        Person jay = new Person("Jay", 20, "watching moive");
        jay.setPetName("gucci");
        jay.setPetspecies("pug");
    }
}

위와 같이 할 경우 객체별로 분리하여 관리할 수 있다.

참고

  • do it! java
profile
안녕하세요.

0개의 댓글