minlog
article thumbnail

 

 

[자바기초 문법] 변수/데이터형 /형변환

패키지를 만들면 그에 따른 폴더 경로도 똑같이 생성된다. 보통 파일 하나당 클레스 하나를 만들어 사용한다. 클레스는 첫글자는 대문자 캐멀(Camel) 스타일을 사용한다. 패키지 이름은 소문자로

jimin-log.tistory.com

변수의 자료형에는 기본 자료형과 참조 자료형이 있다.

참조 자료형 (String,Date,Student  ...)

  • 클래스형으로 변수를 선언
  • 참조 자료형의 크기는 참조하는 자료형에 따라 다름
  • 참조 자료형을 사용할때는 해당 변수에 대해 생성(new)해야함. (ex : Student student = new Student()  , 예외 String 클래스 )

 

 

🍫 참조 자료형 정의하여 사용해보기

Subject.java

package ch09;

public class Subject {
	String subjectName;
	int score;
	int subjectId;	
}

Student.java

package ch09;

public class Student {
	int studentId;
	String studentName;
	
    //참조 변수
	Subject korea;
	Subject math;
	
	public Student() {}
	public Student(int studentId, String studentName) {
		super();
		this.studentId = studentId;
		this.studentName = studentName;
		this.korea = new Subject(); // 참조변수 선언
		this.math = new Subject(); // 참조변수 선언
	}
	
	public void setKoreaSubject(String name, int score) {
		korea.subjectName = name;
		korea.score = score;
	}
	public void setMathSubject(String name, int score) {
		math.subjectName = name;
		math.score = score;
	}
	public void showScoreInfo() {
		int toal = korea.score + math.score;
		System.out.println(studentName+"학생의 총점은"+toal+"입니다.");
	}
	
}

SubjectTest.java >>  main

package ch09;

public class SubjectTest {

	public static void main(String[] args) {
		Student student = new Student(100, "홍당무");
		student.setKoreaSubject("국어", 100);
		student.setMathSubject("수학", 99);
		student.showScoreInfo();
		
		Student studentKim = new Student(101, "김철수");
		studentKim.setKoreaSubject("국어", 70);
		studentKim.setMathSubject("수학", 50);
		studentKim.showScoreInfo();

	}

}
결과값
홍당무학생의 총점은199입니다.
김철수학생의 총점은120입니다.

 

profile

minlog

@jimin-log

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!